Your Source for Learning
Technology, Strategy, and News
ARTICLES       RSS feed RSS feed

Development Tips: Writing Your First JavaScript Application

by Mark Lassoff

March 22, 2012

Column

by Mark Lassoff

March 22, 2012

“Now with our problem stated, we need to come up with a solution. Most programmers would recommend you come up with your solution using pseudo-code. Pseudo-code, also called an algorithm, is an English language description of how to solve the problem.”

Lately, I have found myself telling my clients that JavaScript is becoming the most important programming language (some would call 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 who displays work on the Web — or uses HTML. For those trying to enter the mobile space, JavaScript is critical as well, as it runs in mobile browsers such as mobile safari for iOS and mobile Firefox for the Android device.

What is JavaScript?

JavaScript adds a layer of interactivity to content displayed in a Web browser. I have argued before that the HTML/CSS/JavaScript stack of technologies is a perfect match for mobile eLearning because it is universal – you can write the learning application once and display it in almost any environment with a Web browser. JavaScript is the only actual programming language that a browser understands. Since it’s a programming language it allows the developer to create dynamic (as opposed to static) activity within a browser. Within the mLearning space, you can use JavaScript to evaluate learner’s responses, set up timers, code evaluative activities, and much more.

What You Need

You can complete this tutorial with any text editor. I recommend Komodo edit, a free text editor. I also recommend that you obtain a copy of the Firefox browser with the latest Firebug plug-in. You will find JavaScript easier to understand if you already have an understanding of HTML. The scripts in this article are images, but you can download a text version of this week's scripts here.

Getting Started

At its essence, programming is about problem solving – so let’s define a “problem” that we can solve with JavaScript programming. This may sound a bit simplistic, but correctly defining the problem to solve is one of the most important parts of the development cycle. So let’s spell out our problem:

Problem: We need to ask the user multiple-choice questions and evaluate the answer provided. Furthermore, the program should provide feedback to the user telling them whether their answers were correct or incorrect. If the answer is correct the user should get the opportunity to move on to the next question. If the answer is wrong they should be able to try again.

Obviously, this is a simplified problem for the purpose 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 a solution. Most programmers would recommend that you come up with your solution using pseudo-code. Pseudo-code, also called an algorithm, is an English language description of how we’ll solve the problem.

Here’s the algorithm I came up with to solve our simple problem:

  1. Display the question to the user
  2. Display multiple choice answers to the user
  3. Obtain the user’s answer
  4. Determine if the user’s answer is correct
  5. Tell the user if their answer is correct
  6. If incorrect, determine if subsequent answer is correct
  7. If correct, display link to next question

Now that we have an easy-to-understand way to solve our programming problem, it’s time to start writing code.

Writing the Initial Code

As we write code we’re going to want to keep our algorithm handy and refer to it often. I like to look at each step in the algorithm as a miniature problem to solve. It is often best if you write your pseudo-code so you can write and test each task somewhat independent of the other features. With complex problems and programs, it’s much less overwhelming to solve a series of smaller problems than one bigger problem.

I think we can combine steps one and two into a single step, since for both we’re simply displaying material in the Web browser. This part can be written out using JavaScript’s ‘document.write()’ method which displays content within the browser window. The content we display can have HTML embedded in it if necessary. Type the following into your text editor:

 <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 to be an .html file so the browser recognizes it) and display it in the browser. If you typed everything correctly you should see something like the screenshot below:

Figure 1. Initial JavaScript Code displaying correctly 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. It simply says to the browser, “Be aware  – the following content is JavaScript, not HTML.” When the browser encounters a script tag it starts interpreting the code as JavaScript until it finds a subsequent closing script tag.

The ‘document.write()’ command is used next. It outputs content to the browser window. Notice that you place the content output to the browser window within quotes. Inside the quotes where you would normally use quotes  – for the ID attribute of the span tag, for example – use single quotes. Notice that each separate JavaScript command ends with a semicolon.

Getting Input from the User

According to our algorithm, our next tasks are to get the user’s response and determine whether it’s correct. The correct answer to our question in this case is choice B  – Sacramento. We could get the user’s answer to our question in several ways. In this case it is probably easiest to ask them to click on the correct answer. Then we can determine if what they clicked on is correct. We can use the span tags embedded in the output to help with this process. Let’s re-factor the code we have already written. Update your code in your text editor 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 code inside the double quotes. It’s easy to make a mistake with all of the single quotes embedded in double quotes. Test your code in the browser. If everything is correct, when you click an answer an alert box should appear indicating which answer you choose. The browser should look something like the screen shot below:

 

Figure 2. The alert box pops up in response to the user’s click on a span element within the JavaScript

Besides adding some needed instructions for the user, I have added two critical pieces of script to this iteration of the program. First, the ‘onclick’ commands detect a click on the span and yield control 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 answer we’re going to need a place to display feedback. We’ll do that with a div. 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 user telling them if their answer was correct or incorrect. The continue div at the bottom will be used to display a link to continue to the next question if they selected the correct answer.

We’re going to change the function so that it determines if the user’s answer is correct in the next step.

Change the code for the function so it reads as follows:

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’s break it down. Now, the ‘onclick’ command in the span passes the user’s answer to this function. It passes a value of a, b, c, or d corresponding to the answer selected by the user. We use the ‘if’ statement to determine if the letter passed was ‘b’ and is correct. If it is correct, we display the “Correct Answer” 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 user gives the incorrect answer, an appropriate response is given in white text with a red background.

 

Figure 3. A correct answer is indicated when the user chooses “Sacramento”

In the space of a short tutorial there is, unfortunately, only an opportunity to introduce a tiny fraction of the powerful features of the JavaScript language. I hope you will take your own learning further and master this powerful language!

[Mark Lassoff’s full JavaScript for Beginners course is available to Learning Solutions Readers at a special 50% discount price of $25.00! Visit http://www.learntoprogram.tv/javascript-training-course/ and use the coupon code LS2012 on checkout. Offer expires 5/1/2012]


Topics Covered

(34)
Appreciate this!
Google Plusone Twitter LinkedIn Facebook Email Print
Comments

Login or subscribe to comment

Great article Mark. The only thing that I would add is that once you're ready look at using jQuery. It's a javascript library that makes writing the code a little easier, so of like 'short hand'. Also look at jQuery Mobile.

I just returned from the Learning Solutions conference, and one of the concerns about tablets was choosing an authoring program that could work on multiple platforms. I know coding isn't for everyone, but as you're looking at your choices, you should consider html, css and javascript, especially if platform compatibility is a big issue for you. Plus jQuery Mobile gives you a lot of transitions so that you can emulate transitions you see in iBooks Author.
Thanks for the feedback. I agree-- jQuery is a great library to approach once you start getting used to Javascript. And I highly recommend the HTML/CSS/JS stack for authoring with maximum compatibility.

This will be the topic of my mLearning Conference presentation...
Related Articles