Your cart is currently empty!
Development Tips: Writing Your First JavaScript Application

Lately, I have found myself telling my clientsthat JavaScript is becoming the most important programming language (some wouldcall it a scripting language) in the world. Because it runs in the Web browser,JavaScript has opened a world of powerful techniques to any developer whodisplays work on the Web — or uses HTML.For those trying to enter the mobile space, JavaScript is critical as well, asit runs in mobile browsers such as mobile safari for iOS and mobile Firefox forthe Android device.
Whatis JavaScript?
JavaScript adds a layer of interactivity tocontent displayed in a Web browser. I have argued before that the HTML/CSS/JavaScriptstack of technologies is a perfect match for mobile eLearning because it isuniversal – you can write the learning application once and display it inalmost any environment with a Web browser. JavaScript is the only actualprogramming language that a browser understands. Since it’s a programminglanguage it allows the developer to create dynamic (as opposed to static)activity within a browser. Within the mLearning space, you can use JavaScriptto evaluate learner’s responses, set up timers, code evaluative activities, andmuch more.
WhatYou Need
You can complete this tutorial with any texteditor. I recommend Komodo edit, a free text editor. I also recommend that youobtain a copy of the Firefox browser with the latest Firebug plug-in. You willfind JavaScript easier to understand if you already have an understanding ofHTML. The scripts in this article are images, but you can download a text version of this week’s scripts here.
GettingStarted
At its essence, programming is about problemsolving – so let’s define a “problem” that we can solve with JavaScriptprogramming. This may sound a bit simplistic, but correctly defining theproblem to solve is one of the most important parts of the development cycle. Solet’s spell out our problem:
Problem:We need to ask the user multiple-choice questions and evaluate the answerprovided. Furthermore, the program should provide feedback to the user tellingthem whether their answers were correct or incorrect. If the answer is correctthe user should get the opportunity to move on to the next question. If theanswer is wrong they should be able to try again.
Obviously, this is a simplified problem for thepurpose of this tutorial. Real-life problem statements can be, and usually are,much more complex. Now with our problem stated, we need to come up with asolution. Most programmers would recommend that you come up with your solutionusing pseudo-code. Pseudo-code, also called an algorithm, is an Englishlanguage description of how we’ll solve the problem.
Here’s the algorithm I came up with to solveour simple problem:
- Display the question to the user
- Display multiple choice answers to the user
- Obtain the user’s answer
- Determine if the user’s answer is correct
- Tell the user if their answer is correct
- If incorrect, determine if subsequent answer iscorrect
- If correct, display link to next question
Now that we have an easy-to-understand way tosolve our programming problem, it’s time to start writing code.
Writingthe Initial Code
As we write code we’re going to want to keepour algorithm handy and refer to it often. I like to look at each step in thealgorithm as a miniature problem to solve. It is often best if you write yourpseudo-code so you can write and test each task somewhat independent of theother features. With complex problems and programs, it’s much less overwhelmingto solve a series of smaller problems than one bigger problem.
I think we can combine steps one and two into asingle step, since for both we’re simply displaying material in the Webbrowser. This part can be written out using JavaScript’s ‘document.write()’method which displays content within the browser window. The content we displaycan have HTML embedded in it if necessary. Type the following into your texteditor:
<script>document.write("<strong>What is the capitol of California?</strong>");document.write("<br/><span id='answerA'>San Francisco</span>");document.write("<br/><span id='answerB'>Sacramento</span>");document.write("<br/><span id='answerC'>Santa Barbara</span>");document.write("<br/><span id='answerD'>Palm Springs</span>");</script>Save the file as “question.html” (it needs tobe an .html file so the browser recognizes it) and display it in the browser. Ifyou typed everything correctly you should see something like the screenshotbelow:
Figure 1. Initial JavaScript Code displayingcorrectly in the Firefox Browser
Let’s break down the code used. First is the script tag. This is not actually JavaScript, but an HTML element. Itsimply says to the browser, “Be aware – thefollowing content is JavaScript, not HTML.” When the browser encounters a script tag it starts interpreting the code as JavaScript until it findsa subsequent closing script tag.
The ‘document.write()’ command is used next. Itoutputs content to the browser window. Notice that you place the content outputto the browser window within quotes. Inside the quotes where you would normallyuse quotes – for the ID attribute of thespan tag, for example – use single quotes. Notice that each separate JavaScriptcommand ends with a semicolon.
GettingInput from the User
According to our algorithm, our next tasks areto get the user’s response and determine whether it’s correct. The correctanswer to our question in this case is choice B – Sacramento. We could get the user’s answer to our question in severalways. In this case it is probably easiest to ask them to click on the correctanswer. Then we can determine if what they clicked on is correct. We can usethe span tags embedded in the output to help with this process. Let’sre-factor the code we have already written. Update your code in your texteditor to match the code below:
<script>function answer(answer){ alert("You answered " + answer); }document.write("<h2>Please click the correct answer.</h2>");document.write("<strong>What is the capitol of California?</strong>");document.write("<br/><span id='answerA' onclick=answer('a')>San Francisco</span>");document.write("<br/><span id='answerB' onclick=answer('b')>Sacramento</span>");document.write("<br/><span id='answerC' onclick=answer('c')>Santa Barbara</span>");document.write("<br/><span id='answerD' onclick=answer('d')>Palm Springs</span>");</script>Be especially careful when entering the codeinside the double quotes. It’s easy to make a mistake with all of the singlequotes embedded in double quotes. Test your code in the browser. If everythingis correct, when you click an answer an alert box should appear indicatingwhich answer you choose. The browser should look something like the screen shotbelow:
Figure 2. The alert box pops up in response tothe user’s click on a span element within the JavaScript
Besides adding some needed instructions for theuser, I have added two critical pieces of script to this iteration of theprogram. First, the ‘onclick’ commands detect a click on the span and yieldcontrol to the ‘answer() function’ at the top of the script. The ‘answer()function’ at this juncture simply echoes the user’s answer.
If we’re going to evaluate the user’s answerwe’re going to need a place to display feedback. We’ll do that with adiv. Add the following to the code below the function:
document.write("<div id='result'></div>");document.write("<h2>Please click the correct answer.</h2>");document.write("<strong>What is the capitol of California?</strong>");document.write("<br/><span id='answerA' onclick=answer('a')>San Francisco</span>");document.write("<br/><span id='answerB' onclick=answer('b')>Sacramento</span>");document.write("<br/><span id='answerC' onclick=answer('c')>Santa Barbara</span>");document.write("<br/><span id='answerD' onclick=answer('d')>Palm Springs</span>");document.write("<div id='continue'></div>");We’ve actually added two div’s. The top div, ID’ed as result, will be where we display feedback to the usertelling them if their answer was correct or incorrect. The continue div at thebottom will be used to display a link to continue to the next question if theyselected the correct answer.
We’re going to change the function so that itdetermines if the user’s answer is correct in the next step.
Change the code for the function so it reads asfollows:
function answer(answer){ if(answer=="b") { document.getElementById("result").innerHTML = "<h1>Correct Answer!</h1>"; document.getElementById("result").style.backgroundColor = "#00CC00"; document.getElementById("result").style.color = "#FFFFFF"; document.getElementById("continue").innerHTML = "<a href='next.html'>Next Question</a>"; }else { document.getElementById("result").innerHTML = "<h1>Sorry, Incorrect! Try again</h1>"; document.getElementById("result").style.backgroundColor = "#CC0000"; document.getElementById("result").style.color = "#FFFFFF"; }}There’s quite a bit going on here, so let’sbreak it down. Now, the ‘onclick’ command in the span passes the user’s answerto this function. It passes a value of a, b, c, or d corresponding to theanswer selected by the user. We use the ‘if’ statement to determine if theletter passed was ‘b’ and is correct. If it is correct, we display the “CorrectAnswer” message. I also changed the background color of the result div to green and the color of the text to white. Finally, if the answer is correct the‘continue’ div is used to display a link to the next page. If the usergives the incorrect answer, an appropriate response is given in white text witha red background.
Figure 3. A correct answer is indicated whenthe user chooses “Sacramento”
In the space of a short tutorial there is,unfortunately, only an opportunity to introduce a tiny fraction of the powerfulfeatures of the JavaScript language. I hope you will take your own learningfurther and master this powerful language!
[Mark Lassoff’s full JavaScript for Beginnerscourse is available to Learning Solutions Readers at a special 50% discountprice of $25.00! Visit https://www.learntoprogram.tv/javascript-training-course/ and usethe coupon code LS2012 on checkout. Offer expires 5/1/2012]