Here - The Times
Transcription
Here - The Times
lEARN TO CODE STNMAST2008 1 IN DAY PART ONE: mAkE YOUR OWN APP THESuNDAyTImES.CO.uk/LEARNTOCODE LEARN TO CODE PART 1 TO mAkE yOuR APP gO TO thesundaytimes.co.uk/learntocode Embrace your inner geek: and get coding today As technology becomes central to our lives, computer coding is the new literacy. Follow these simple steps and become part of the revolution, says Eleanor Mills C omputers are embedded in our lives. We spend an average of eight hours a day in front of screens, and we are seeing technology revolutionise the economy, whether it’s AirBnB changing the way we go on holiday, or Uber shaking up the taxi industry. Technology is key to all our of futures, yet only a handful of us understand the language that makes computers work. This week – finally - computer coding becomes part of the national curriculum in schools, so what better time to introduce all Sunday Times readers to the basics of coding and give kids a head start. Don’t be put off by the idea that it is too difficult – everyone can discover their inner geek. Today, we provide you with a step-by-step guide to how create your own app. It really is possible to learn how to do it by following the instructions over the next few pages. Decoded, who have provided the materials, teach these steps to professionals every day (at a cost of £700 per person). I was lucky enough to do their course with a group of women including supermodel Lily Cole and Mumsnet founder Justine Roberts this year. The column I wrote describing the experience received so much feedback we decided to open the experience up to our readers, made possible through Decoded’s new set of online tools, called Playto.io, which they’ve developed to enable anyone to be come a digital creator. Kathryn Parsons, chief executive and co-founder of Decoded, says: “We desperately need digital creators - talent – for the UK to be a global player in tech. Coding is the new building block for the world. There are lots of intelligent, energetic young people out there but only a fraction of them are learning to code on the web. It is great that the UK is introducing coding to the curriculum but bringing coding alive is essential, not just in the classroom but by parents sitting down with their kids and learning together. Whether you are six or 60 this has a place in everyone’s lives. Coding is the new literacy.” She is right – enjoy making your app. Next week we will show you how to extend it, add more tools and make it even better. We’re going to build an app. We’re sure you’ll have lots of ideas for apps you’d like to make. To keep things as simple as possible, we’re going to build an app together. “It is great that the uk is introducing coding to the curriculum but bringing coding alive is essential, not just in the classroom but by parents sitting down with their kids and learning together. We’ve created Playto.io to enable anyone, whether you are six or 60, to join the digital revolution!” ! the brieF STNMAST2008 1 wireFraming The planning process is absolutely vital when building an app. If you just sit down and start sketching it’s possible to explore multiple options for what your app could do and look like. There are many tools for making basic prototypes. But nothing beats a pencil and paper. The key thing is to get the idea out of your head and into a medium where you can play around with it. A huge part of the development process is Googling, reading, thinking, sketching. Let’s get to it. C. Add the score wireFrames Wireframes are basic designs that are useful for planning the user experience before a single line of code is written. Originally, wireframes tended to be long lists of specifications and page elements but today they are often visual representations of the app or website that is going to be built. If you’re thinking of commissioning an application, or working with a developer, providing a wireframe (however sketchy!) is a good starting point A. As a list D. Finish B. One by one Build a multi-platform app that lets you set quizzes for your friends. Kathryn Parsons, chief executive of Decoded 1 wireFraming/iDeas We will start by wireframing the app. This will involve sketches and a basic plan of what it will do. 2 content It would be nice to display a running score. Let’s mock that up. We’ll then work on defining the content and setting up our page. 3 Design With our basic content in place, we can focus on the design of our app. 4 interactiVity Once it looks right, we can turn our attention to the behaviour. How do we ask questions? How do we keep score? For our purposes, let’s display the questions one by one. It’s simpler and more focused. Once they’ve finished the quiz, how about we let them share their results on Facebook to challenge their friends? NEXT UP We now know what we need to build and what it’s going to look like. let’s dive into the hTml  LEARN TO CODE PART 1 “When somebody has learnt how to program a computer … you’re joining a group of people who can do incredible things. They can make the computer do anything they can imagine.” TO mAkE yOuR APP gO TO thesundaytimes.co.uk/learntocode Sir Tim Berners-Lee, inventor of the web STNMAST2008 2 content Every web page and many of the apps you know and love use HTML. It allows us to tell the browser what everything is – our logos, paragraphs, any images, videos and so on. HTML is a universal language – it is understood by every browser, and all smartphones, including iPhones and Android, can run apps coded using HTML. To create your app, you’ll need to use our Playto editor. To load up the editor: Open an up-to-date browser (we recommend Firefox or Google Chrome). Navigate to thesundaytimes.co.uk/learntocode Login using one of the options provided Create a new project in the Playto Editor Replace the hello world text with the name of your app. We’re going to call ours iQz. We need to tell the browser this is our heading, so we wrap it in an <h1> tag: <h1>iQz</h1> Next we need to put in a list of questions and answers: <h1>iQz</h1> <p>What is the capital of Russia? <span class="correct">Moscow</span> <span>Mosheep</span> </p> Here we have one question inside a <p> element, and then we have two options. Both options are put inside <span> elements. The correct one we give a “class” of correct. This means that later on we can do things like check if the user got it right Let’s put some more questions in. Whatever you do, don’t copy us! Think of your own quiz to test your friends :) <h1>iQz</h1> <p>What is the capital of Russia? <span class="correct">Moscow</span> <span>Mosheep</span> </p> <p> What noise do cows make? more structure. All html pages are made up of two sections: the <head> for information about the page, and the <body> for content the user sees. The content we’ve already written will therefore go in the body: html: the language oF content HTML, which stands for HyperText Markup Language, was developed by the inventor of the web, Sir Tim Berners Lee in 1989. The original idea behind HTML was to write an open set of rules so that any browser could interpret a piece of content and know where there were paragraphs, headings, lists and so on. Sir Tim’s idea was to allow the transfer of information between different computers, and so HTML is purely a language of content. The fact that HTML is a “markup language” means that rather than writing rules and instructions for a computer, we are simply “marking up” content with tags. <span class="correct">Moo</span> <span class="correct">Oui</span> <span>Euuuuuuuur</span> </p> <p> What is the meaning of life? <span class="correct">42</span> <span>No idea</span> </p> Great. If you preview your app in the browser (by clicking “View App”) you will notice that there’s no title in the tab at the top. We need to give the app its own name, which means adding in a bit <title>iQz</title> HTML 5 an eVolVing stanDarD Today, HTML is constantly evolving and developing as new features come out. If you use a browser like Chrome updates will happen in the background, meaning that you’ll always have the latest version. Design Create a new file by clicking on the plus icon in the left-hand bar. Name it “style.css” all lowercase. We will need to change the colour of our <h1> now. We’ve set ours to white. CSS works by targeting HTML elements and giving them a list of style instructions. If you think about it, any particular part of a design could be described by how it looks. This is what we do with CSS. You say things like: I want my <h1> to be big, bold, red and centred: Looking at our wireframe, we want to only display one question at a time. Using JavaScript later on, we can show or hide different questions based on where they are. So for now, let’s hide all the questions, and then just display the first one: h1 { </head> font-size: 48px; <body> <h1>iQz</h1> color: red; <p> font-weight: bold; What is the capital of Russia? text-align: center; } <span class="correct">Moscow</span> <span>Mosheep</span> </p> <p> … </p> </body> </html> Refresh your page now - your title should be displaying. You now have the bare bones of your app up and running. That wasn’t too hard, was it?! The indentation is purely there to show us as coders what’s where. The browser ignores “white space”. It does look neater, doesn’t it? It’s up to you, but we like to keep our code nice’n’tidy. Lastly for now, let’s put in something to hold our score: the separation oF concerns You’ll notice that with just HTML your web-app won’t look that exciting. This is because we haven’t included any design yet. In web development we talk about the idea of the “separation of concerns”, which means having separate languages and files for content, design and interactivity. <p> … </em> </body> </html> We’ve used an <em> element (which means it is emphasised) with two spans in it – one to hold the running score, the other the total number of questions. For now we’ve just made up the numbers; we will populate these from the JavaScript later on. CSS stands for Cascading Style Sheets. It was developed by Håkon Wium Lie and Bert Bos in the early 1990s. Fundamentally, CSS gives developers the ability to breathe life into HTML - colours, borders, backgrounds and more. We’ll be showing you a variety of CSS commands. <link rel="stylesheet" href="style.css"> color: white; attribute Attributes are pieces of information about an element on a page. In this case our “correct” attribute is used to tell the browser which answer is correct. What’s great is that unless our user looks at the source code, they won’t be able to see which answer has been marked as correct. background: red; font-family: Helvetica; max-width: 500px; margin-right: auto; margin-left: auto; text-align: center; } ... } p { display: none; } p:nth-of-type(1) { display: block; nth-of-type(n) is what’s called a pseudo-selector; it allows you to get one of a specified group of elements. Please note, the authors had to Google “targeting first paragraph with CSS” as it’s not something we’d done before! As a coder, you’re not expected to know all the answers. Search engines are always right there – it doesn’t make sense trying to remember all the commands, and we’re all learning all the time! <title>iQz</title> body { font-weight: bold; We start by targeting all paragraphs and setting their display property to “none”. Then, we target just the first question and set its display property to “block”, which is CSS’s way of saying “show”. <head> Aa the importance oF cases You may have seen that whether you type in upper or lower case matters sometimes when you’re coding, but not all the time. It’s normally best practice to keep everything lowercase when you are coding in HTML and CSS to make sure you can always reference files and elements extra step: Fonts If you’re feeling brave, why not add a custom font to your web app. Google has a great tool called “Google Fonts” which allows you to import a font directly into your page. Just Google it! h1 { } We need to tell the browser to read our CSS file. It doesn’t magically know it’s there. When the browser loads the app, it downloads just one file: our index.html. So, it’s important we tell it to read any new files we use, and we do this in the <head> of our index.html Let’s change the background to a nice bold colour. we’re going to use the <body> tag to set some base styles in our style.css Your score is <span>5</span> It hasn’t worked, has it? Great! Our heading should now be big, bold, red and centred! <em> / Problem! We use the <link> element to point to our new file. We tell the browser it’s a stylesheet and use the “href” attribute to give it the location of our file. We’ve added in a message to give people that will be hidden until the end of the quiz <span class=“score”>0</span> We use colons at the end of the style property we want to set, and semi-colons at the end of each line to tell the browser we’ve finished. css: the language oF Design </head> <p id=“final”>That’s the end of the quiz!</p> </p> What is the French for "yes"? <head> When HTML was created there were other competing markup languages. One of the reasons why HTML has become so ubiquitous across the world is because Sir Tim decided to make it completely open. This means that if you right click on any page on the web and select “view page source” you will be able to see the raw HTML that makes up the page. </p> <span>Baah</span> <p> <html> 3 a raDically open language HTML on its own is boring. Everything is black and white. You might find this bleak minimalism appealing… we don’t – our app needs to come alive! CSS is the language of style and design. We use it to tell the browser what HTML elements should look like. By specifying design properties like height, width, colour and background, we can take our unstyled HTML and create a user interface that is beautiful and intuitive. You should now have just one question showing. Let’s style up the answer boxes by targeting the <spans> inside the <p>s and making them big and bold. Let’s also make the paragraphs a bit bigger and make them bold as well. We’ve already done this for the heading, so this bit should be a doddle :) ... p { display: none; font-weight: bold; font-size: 24px; } p:nth-of-type(1) { display: block; } p span { be as creatiVe as you like Once you understand the principle of CSS you can add as many rules for each bit of the page as you like. What’s great too is that they’re all interchangeable, so if you know how to change the font-size of a heading, you can change the fontsize of a paragraph (or anything else you like!) ERROR! DON'T PANIC First, open your web-app in full screen view (just click the “view your app” button in the top right corner), and then right click anywhere in your web-app. Select “inspect element” from the menu and a bar should pop up. This is a developer tool designed for bug fixing! If you click on “console”, you should be able to see if there are any errors on your page. On the left hand side you’ll see a description of the error, and on the right hand side you’ll see the file where the error is, a colon and a number. This is the line number where your error is coming from. Inevitably it won't always work. If you get an error message go back through and check every line and comma very carefully. Then check the detail of your error message for clues. If that doesn't work, help is at hand at our forum playto.io.org key in your question and everything will be ok LEARN TO CODE PART 1 To make your app go to thesundaytimes.co.uk/learntocode “CSS enables me not only to design beautiful and flexible interfaces, but also allows the re-use of design patterns. It saves time and helps to keep designs consistent across projects.” 4 javascript Jonas Haefele, designer display: block; text-align: center; padding: 10px; Extra step: COlours in CSS There are a set number of “word colours” that have already been defined by developers, but if you want to truly customise your design you’ll need to pick your own. To do this, you can go to colorpicker.com, and you’ll see that each colour has an R, G and B value (standing for red, green, blue). Just select a colour you like, and then copy the RGB colours to your CSS. For example, you might change your heading colour to a lovely shade of pink: h1 { color: rgb(222, 38, 210); } If you’d like to have a bit of transparency in your colour, you can also give it an “alpha” value between 0 and 1, with 0 being completely transparent and 1 being completely opaque. margin: 10px; border: 1px white solid; } Padding is the space around the inside of an element, between the content and the border. Margin is the space around the outside. We’ve used “p span” as we only want to target <spans> that are inside paragraphs. Wouldn’t it be nice if the buttons changed when you hovered over them? We can do this by defining an extra list of styles for when it’s hovered over (with “:hover” being another pseudo-selector!) p span { It’s all well and good having a beautifully designed page. But if it doesn’t do anything, it’s a bit pointless. JavaScript is a programming language. It enables us to tell the app to respond to certain events, compute certain calculations, and essentially do the things we want it to do. In our case, this is to behave like an interactive quiz that asks a series of questions and saves the score. But you can do anything you can imagine using a programming language. The only limit is the speed of your hardware and your own imagination! All programming languages are made of the same three ideas: Variables fl Data Functions fl Actions Logic fl Decisions zVariables are the bits of information the program is concerned with. z Functions are predefined sections of code that do a certain thing. z Logic is the decisions the code needs to make at any given time. ... border: 1px white solid; Let’s do this together. p span:hover { cursor: pointer; background: rgba(205,100,100,0.5); } Finally, let’s style up our score box. We want it to appear at the bottom of the page and stick there: em { position: fixed; bottom: 0px; left: 0px; font-size: 30px; Variables: We’ll need a score. We’ll need to know what question we’re on. We will also need to know the total number of questions. Can you think of any others? I can’t! Functions: We will need to: z determine whether the user has answered the question correctly z increment the score z move to the next question </em> <script src="//code.jquery.com/jquery-1.11.0.min. js"></script> <script src="quiz.js"></script> .js JavaScript: The Language of Interactivity JavaScript is the only programming language that can be used in web browsers. It’s great to use it whenever we need to write rules or instructions. For our web-app, we want to be able to record people's scores, and also tell whether they got the question right or wrong. We’ll need to save some variables (pieces of data), test these variables with some logic and then depending on the logic, run some functions. var questionNumber = 1; To keep a check on what question our user is on. We’ll then use this line: var score = 0; To check what our user’s score is. We now need a function to show the relevant question, so that when our user is on questionNumber, they’ll only see the first question. To define a function, we write the following line: function showQuestion(question) { } Everything within the function goes between the curly brackets. The (question) bit of the function is the argument - or an input, which will allow us to tell the function what question our user is on. Once we’ve defined the function, we need to hide all of the questions and then only show the question that the user is on. To do this, we need to add two lines inside our function, so that it looks like this. function showQuestion(question) { $('p').hide(); $("p:nth-of-type("+ question + ")").show(); } showQuestion(questionNumber) Let’s get cracking. Create a new file called quiz.js. We need to tell the browser to read it. Unlike CSS, we generally do this from the bottom of the HTML page; this is so browsers can read the HTML and CSS first, which means the app will load faster: $('span').click(function() { ... width: 100%; </em> background: red; <script src="quiz.js"></script> } </body> </html> Now that our JS file is connected, let’s do a little test to see if it’s working. If you write the following in your quiz.js file, a pop up box should appear: alert(“Hello World!”); If you didn’t, double-check your script is connected properly, and make sure your browser is not blocking popups. Once you’re happy that your showQuestion function works, you can delete the above line. Now this function is set up, we can create a function that will run when our user clicks on an answer. Like before, we set up a function, but this time we use jQuery to detect when a user clicks on a span. Make sure your file name is all lowercase. Refresh your page to make sure it’s updated. Ensure that you have no spaces between the word alert and the opening bracket. Still stuck? Ask a friend to look over it with you. Fixing things is half the fun! $('span').click(function() { The Power of Libraries }); if ($(this).hasClass("correct")) { score++; } jQuery is a JavaScript library written originally by John Resig. A library is a collection of pre-written code that we can access. $('.score').html(score); questionNumber++; showQuestion(questionNumber); }); That’s it! The last thing we’ve got to do is just run the showQuestion function when the user first loads the page. To do this we just use a really simple line: Now we’ve got the jQuery library connected we can start to write the variables we need to get our quiz to work. At the top of your quiz.js file, we need to define the following variable. We’ll use this line: We’re using the jQuery show and hide functions to hide all of the question paragraphs and then show only the question that the user is on. Why not have a go at testing the function now by calling it for the first question? Type the below and see what happens! BUG TESTING STNMAST2008 Now that we’ve checked if our user got the question right or not, we need to show them the next question. We can do this by adding one to our question number variable, and then running the showQuestion function that we’ve already created. </html> Logic: z What logical decisions might we make? z “if user clicked on a span with a class of correct, increment the score and move to the next question” z if there are no more questions, show the facebook share button z Note how logic makes use of our functions and variables. Logic is the glue that holds a program together. padding: 10px 0px 20px 0px; We’ve given it the same background colour as the rest of the page. This means that if your questions are very long, they will scroll behind the score. The instruction for padding is the equivalent of writing: padding-top: 10px; padding-right: 0px; padding-bottom: 20px; padding-left: 0px; You can put them all on one line to save time. ... </body> It’s always helpful to break down your desired outcome into the variables, the functions and the bits of logic we’ll need to write. } h1 { color: rgba(222, 38, 210, 0.8); } Let’s delete the alert now we know it’s working. As well as including our JavaScript file, we’ll also need to include a link to jQuery, which will allow us to use code developed by other developers to supercharge our web app. To include jQuery, Google ‘jQuery CDN’ and look for a line similar to the below. Head back to your index.html file, and insert the line at the bottom of your HTML file, before you link to quiz.js. This will link to a version of jQuery hosted on a Content Delivery Network. showQuestion(questionNumber) Content Delivery Network (CDN) A content delivery network is an idea meaning that a file or service is hosted on computers around the world, so that wherever your users are they’ll be able to access the file quickly and easily Oh! One more thing. The last thing we need to do in our showQuestion function is check that the user hasn’t finished the quiz. If they have, we want to show them the final screen. To do this, we’ll use our first piece of logic. We can get jQuery to detect if the next question exists. If it does, we’ll show that question. If it doesn’t, we can assume that the user is at the end of the quiz and show them the final screen. function showQuestion(question) { $('p').hide(); if ($("p:nth-of-type("+ question + ")").length > 0){ $("p:nth-of-type("+ question + ")").show(); } else { $("#final").show(); cC Camel Casing You may be wondering why we call our variables and functions names like questionNumber. It’s because when you have long function names it’s easier to read them when the first letter of each word (apart from the first) is capitalised. Look at this for an example: thisIsALongFunctionNameThatIsCamelCased thisisalongfunctionnamethatisnotcamelcased } } Now we’ve pieced all the code together, your quiz.js should look like this: var questionNumber = 1; var score = 0; function showQuestion(question) { $('p').hide(); if ($("p:nth-of-type("+ question + ")").length > 0){ $("p:nth-of-type("+ question + ")").show(); } else { $("#final").show(); } } $('span').click(function() { if ($(this).hasClass("correct")) { When a user clicks on an answer, the first thing we want to do is detect if the user is correct or not. We can use some logic to do this. It will be an “if” statement that will check if the answer has the class “correct”. If it does we’ll add 1 to the user’s score using JavaScript’s ++ command. Once this is done we can update the score to show the user how many questions they’ve got right. $('span').click(function() { if ($(this).hasClass("correct")) { score++; } $('.score').html(score); }); score++; } $('.score').html(score); Nth-of-type The nth-of-type selector allows us to select an element and detect what order it is on the page. This means that we’re able to give our users the quiz questions one by one, rather than all at once. questionNumber++; showQuestion(questionNumber); }); showQuestion(questionNumber) If you click “view your app” you should now have a fully functioning quiz application! We used jQuery for our programming, but if you’d like to see how you’d write this program without jQuery check out our website. DON’T WORRY, bE ‘APPY Build your own app with The Sunday Times and then share it with us to be in with a chance of spending the day in the newsroom with our digital team. We’re looking for the most imaginative apps that show you’ve gone beyond our guides to produce a unique, interesting and – most importantly – functional app. Share YOUR APP ON TWITTER USING #STCodeComp to be in with a chance of winning. The competition will be judged by both The Sunday Times and Decoded, so this could be your opportunity to be recognised by the best! Terms and conditions apply. Visit thesundaytimes.co.uk/apprules for more details