d-V_UA4

edenenterprises
  • No tags were found...

d-V_UA4

LEARN TO CODE PART 1To make your app go tothesundaytimes.co.uk/learntocode“CSS enables me not only to designbeautiful and flexible interfaces, but alsoallows the re-use of design patterns. Itsaves time and helps to keep designsconsistent across projects.”Jonas Haefele, designerExtra step:COlours in CSSThere are a set numberof “word colours” thathave already been definedby developers, but if youwant to truly customiseyour design you’ll need topick your own.To do this, you can goto colorpicker.com, andyou’ll see that each colourhas an R, G and B value(standing for red, green,blue). Just select a colouryou like, and then copy theRGB colours to your CSS.For example, you mightchange your headingcolour to a lovely shadeof pink:h1 {color: rgb(222,38, 210);}If you’d like to have a bitof transparency in yourcolour, you can also give itan “alpha” value between0 and 1, with 0 beingcompletely transparentand 1 being completelyopaque.h1 {color: rgba(222,38, 210, 0.8);}}display: block;text-align: center;padding: 10px;margin: 10px;border: 1px white solid;Padding is the space around the inside of an element,between the content and the border. Margin is thespace around the outside. We’ve used “p span” as weonly want to target that are insideparagraphs.Wouldn’t it be nice if the buttons changed when youhovered over them? We can do this by defining anextra list of styles for when it’s hovered over (with“:hover” being another pseudo-selector!)p span {...border: 1px white solid;}p span:hover {}cursor: pointer;background:rgba(205,100,100,0.5);Finally, let’s style up our score box. We want it toappear at the bottom of the page and stick there:em {position: fixed;bottom: 0px;left: 0px;font-size: 30px;padding: 10px 0px 20px 0px;width: 100%;background: red;}We’ve given it the same background colour as therest of the page. This means that if your questions arevery long, they will scroll behind the score. Theinstruction for padding is the equivalent of writing:padding-top: 10px; padding-right: 0px;padding-bottom: 20px; padding-left: 0px; Youcan put them all on one line to save time.4javascriptJavaScript is a programming language. It enables us to tell the app torespond to certain events, compute certain calculations, and essentiallydo the things we want it to do. In our case, this is to behave like aninteractive quiz that asks a series of questions and saves the score. Butyou 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 DataFunctions fl ActionsLogic fl DecisionszVariables 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.It’s always helpful to break down your desired outcome into thevariables, the functions and the bits of logic we’ll need to write.Let’s do this together.Variables:We’ll need a score. We’ll need to know what question we’re on. We willalso need to know the total number of questions. Can you think of anyothers? I can’t!Functions:We will need to:z determine whether the user hasanswered the question correctlyz increment the scorez move to the next questionLogic:z What logical decisions might we make?z “if user clicked on a span with a class of correct, increment the scoreand move to the next question”z if there are no more questions, show the facebook share buttonz Note how logic makes use of our functions and variables. Logic is theglue that holds a program together.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; thisis so browsers can read the HTML and CSS first, which means the appwill load faster:...Now that our JS file is connected, let’s do a little test to see if it’sworking. If you write the following in your quiz.js file, a pop up boxshould appear:alert(“Hello World!”);It’s all well and goodhaving a beautifullydesigned page. But if itdoesn’t do anything,it’s a bit pointless.If you didn’t, double-check your script is connected properly, and makesure your browser is not blocking popups..jsJavaScript:The Languageof InteractivityJavaScript is the onlyprogramming languagethat can be used in webbrowsers. It’s great to useit whenever we need towrite rules or instructions.For our web-app, wewant to be able to recordpeople's scores, and alsotell whether they got thequestion right or wrong.We’ll need to save somevariables (pieces of data),test these variables withsome logic and thendepending on the logic,run some functions.BUGTESTINGMake sure your filename is all lowercase.Refresh your page tomake sure it’s updated.Ensure that you haveno spaces betweenthe word alert and theopening bracket.Still stuck? Ask afriend to look over itwith you. Fixing thingsis half the fun!Let’s delete the alert now we know it’s working. As well as including ourJavaScript file, we’ll also need to include a link to jQuery, which will allow us touse code developed by other developers to supercharge our web app.To include jQuery, Google ‘jQuery CDN’ and look for a line similar to thebelow. Head back to your index.html file, and insert the line at the bottom ofyour HTML file, before you link to quiz.js. This will link to a version of jQueryhosted on a Content Delivery Network....Now we’ve got the jQuery library connected we can start to write the variableswe need to get our quiz to work. At the top of your quiz.js file, we need to definethe following variable. We’ll use this line: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 relevantquestion, so that when our user is on questionNumber, they’ll only see the firstquestion.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 thefunction what question our user is on.Once we’ve defined the function, we need to hide all of the questions andthen only show the question that the user is on. To do this, we need to add twolines inside our function, so that it looks like this.}function showQuestion(question) {$('p').hide();$("p:nth-of-type("+ question + ")").show();We’re using the jQuery show and hide functions to hide all of the questionparagraphs 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 firstquestion? Type the below and see what happens!showQuestion(questionNumber)Once you’re happy that your showQuestion function works, you can delete theabove line.Now this function is set up, we can create a function that will run when ouruser clicks on an answer. Like before, we set up a function, but this time we usejQuery to detect when a user clicks on a span.$('span').click(function() {});When a user clicks on an answer, the first thing we want to do is detect if theuser 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’lladd 1 to the user’s score using JavaScript’s ++ command. Once this is done wecan 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);});The Power ofLibrariesjQuery is a JavaScriptlibrary written originallyby John Resig. A library isa collection of pre-writtencode that we can access.ContentDeliveryNetwork (CDN)A content delivery networkis an idea meaning thata file or service is hostedon computers around theworld, so that whereveryour users are they’ll beable to access the filequickly and easilycCCamelCasingYou may be wonderingwhy we call our variablesand functions names likequestionNumber. It’sbecause when you havelong function names it’seasier to read them whenthe first letter of eachword (apart from the first)is capitalised. Look at thisfor an example:thisIsALongFunction-NameThatIsCamelCasedthisisalongfunctionnamethatisnotcamelcasedNth-of-typeThe nth-of-type selectorallows us to select anelement and detect whatorder it is on the page.This means that we’reable to give our users thequiz questions one by one,rather than all at once.STNMAST2008Now that we’ve checked if our user got the question right or not, we need toshow them the next question. We can do this by adding one to our questionnumber variable, and then running the showQuestion function that we’vealready created.$('span').click(function() {if ($(this).hasClass("correct")) {score++;}$('.score').html(score);questionNumber++;showQuestion(questionNumber);});That’s it! The last thing we’ve got to do is just run the showQuestion functionwhen the user first loads the page. To do this we just use a really simple line:showQuestion(questionNumber)Oh! One more thing. The last thing we need to do in our showQuestion functionis check that the user hasn’t finished the quiz. If they have, we want to showthem the final screen. To do this, we’ll use our first piece of logic. We can getjQuery 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 showthem 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();}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")) {score++;}$('.score').html(score);questionNumber++;showQuestion(questionNumber);});showQuestion(questionNumber)If you click “view your app” you should now have a fully functioning quizapplication! We used jQuery for our programming, but if you’d like to see howyou’d write this program without jQuery check out our website.


DON’T WORRY,bE ‘APPYBuild your own app withThe Sunday Times and then shareit with us to be in with a chance ofspending the day in the newsroomwith our digital team. We’re lookingfor the most imaginative apps thatshow you’ve gone beyond our guidesto 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

Similar magazines