Introduction to JavaScript Fall 2009 Class 4

esse quam videri
Revision as of 22:41, 28 September 2010 by Matthew.ephraim (talk | contribs) (Undo revision 17725 by Matthew.ephraim (Talk))
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Back to Introduction to JavaScript Fall 2009

Introduction

This week I will talk about using some of the concepts I've shown you the last few weeks to actually start putting together a web page that uses JavaScript. I want to make sure that everyone understands the concepts I've presented so far are making sense to everyone, so the majority of the class will be dedicated to building a simple game that tests your knowledge. This game will be your assignment for the week, but hopefully you will be able to finish it during class time.

Before starting the game, there are a few coding style issues that I'd like to cover.

Coding Style

One thing that I haven't talked about is coding style. Like the English language, JavaScript has it's own styles that you should follow if you want to make your code readable for others (and, of course, for yourself).

The Mozilla JavaScript Style Guide is a comprehensive list of rules that you should try to follow when writing JavaScript. Some of the rules are more important than others, and many of them might not make sense yet for a beginner class. I've listed a few of the rules that apply for this class so far.

Variables and Functions

Clear Naming

Your variables and functions should have names that clearly indicate what the variable is being used for or what the function does. For example, the following variable is being used to store a person's name:

  var n = "Matthew Ephraim";

This is a bad variable name, because n doesn't tell you anything about what the variable is used for, so it might be confusing later on. A much better name would look like this:

  var name = "Matthew Ephraim";

This name is better because name tells you what the variable is being used for.

Multiple Word Names

When your variable or function names have multiple words in them, it's JavaScript style to use camel case (aka camelCase) to indicate that the variable names are multiple words. For example, this variable name is made up of 2 words:

  var professorname = "Matthew Ephraim";

It's 2 words, but it's also difficult to read. It can be made clearer by using camel case:

  var professorName = "Matthew Ephraim";

Notice that the N is capitalized now. This makes it easier to see where the 2 words are separated. Variables names can't have spaces in them, so this is a simple way to still use 2 words in the variable name. Longer variables names with multiple words can be used as well:

  var professorFullName = "Matthew Ephraim"; // professor full name, 3 words
  var firstClassStartTime = "6:30pm"; // first class start time, 4 words

Indentation

Another important coding style is using proper indentation in your code. Just like indenting the first sentence of a paragraph can make text easier to read, indenting your code properly can make it easier to read as well. Typically, when you switch to a new block of code, you should indent 2 spaces.

Remember that, in JavaScript, bocks are sections of code that are surrounded by { curly brackets }. So, every time you're using an opening curly bracket, you should indent 2 spaces. The code example below doesn't use any indentation:

  function alertMatt()
  {
  if (name === "Matt")
  {
  alert('hello Matt');
  }
  else
  {
  alert('You're not Matt!');   
  }
  }

Is this code easy to read? How about if it was indented:

  function alertMatt()
  {
      if (name === "Matt")
      {
          alert('hello Matt');
      }
      else
      {
          alert('You're not Matt!');   
      }
  }

Is this code easier to read? The code that goes with the function is indented several spaces, and the code that's associated with the if statement and with the else statement is also indented several spaces more. Most good text editors should have a feature that help you properly indent your code.

Links

Activity

Today, we will be creating a simple number guessing game. The computer will pick a random number and the user will try to guess what the number is. If the user guesses too low, the computer will tell them that the number is higher. If the user guesses too high, the computer will tell them that the number is lower. And if the user guesses the number correctly, the computer will tell them that they have won.

Step 1

get the template

First, download the template for the game. I have already created a game board for you. The board has a few elements on it and is styled using CSS. Open up game.html and look at the html. There is a form with an input box for the number that the user will guess. There is also a button that the user can click to send their guess to the computer. Finally, there is a div at the bottom where messages from the computer will be displayed.

Notice that 3 of the elements have the id attribute filled out. We are going to use those ids in our JavaScript.

Step 2

test the setupGame function

Open the file called behavior.js that's in the JavaScript folder. This is the file that contain the program for our game. Notice that I have already created several functions in the file for you. For now, you can ignore the 2 functions at the bottom of the page. We will be using these functions later on to make the game work.

The 2 things that I want you to notice are the empty function called setupGame and the link that says:

  window.onload = setupGame;

This line is important. window is a variable for the browser window and onload lets you set a function that will run when the browser window loads. So, what this line of code is saying is "call the function setupGame when the browser window loads". In other words, setupGame is the name of a function that should run as soon as the page loads.

Right now setupGame isn't actually doing anything, because it's empty. Modify the function so that it looks like this

  function setupGame()
  {
      alert('this is a test');
  }

The line we added will simply pop up a test message when the page loads. Reload game.html page to make sure it works. If everything is working you'll see a message popup when you reload the page.

Step 3

setup the random number

Also notice that the behavior.js has a variable called randomNumber declared at the top. Unfortunately, it doesn't help us at all, because it's not set to anything yet. Woudn't it would helpful if our setupGame function set that variable to a random number? I have created a function called getRandomNumber that returns a random number. Call the function and set the return value equal to the randomNumber variable.

Step 4

create a guess function

Earlier, I said we would be using the ids on the html elements in our JavaScript. In this step we will be finding the button on the page using JavaScript and then setting the button up so that when it's clicked on, it will call a function.

First, create a function called guess. This will be the function that we'll use to take a guess at what the number is. We want this function to get called the user clicks the guess button. For now, put in another test alert, so that we can test to make sure the function is getting called when we click the button.

make the guess button work

Now, we can find the guess button and make it so that when you click on the guess button the guess function gets called. JavaScript has a function called document.getElementById(). You use this function to find html elements on the page using the id that you gave them. For example, this is how you would find the guess button and store it in a variable:

  var guessButton = document.getElementById("guess");

The document.getElementById() function takes in one parameter, which is the id of the element you want to find. If you look at the html for the project again, you can see that there is only on html tag that has the id guess. The element with the id of guess is the one that the call to document.getElementById("guess") finds.

Once the button is found, it gets stored in the variable called guessButton. We can use the variable to make the button do something when it's clicked on. To do this, we'll use something called an event handler. We'll talk about event handlers more in depth in another class. This week I just want to you set the onclick handler to your guess function, so that when the button gets clicked, the guess function gets called.

You've already seen how to find the guessButton. The next code example shows you how to set the onclick handler on the button you've found:

  guessButton.onclick = guess;

The line of code is simply saying: when a user clicks guessButton call the guess function. Take the 2 lines that find the button and set the handler and put them in your setupGame function, so that they look like this together:

  var guessButton = document.getElementById("guess");
  guessButton.onclick = guess;

You can also remove the test alert in the setupGame function. We won't need it anymore. If you've done everything correctly, you should be able to reload the page and then click on the guess button. When you click on it, you should see an alert box that pops up.

Step 5

find the message area

For the next step, you want to make it so the guess function updates the message area when the button is clicked. For now, we'll just send a test message to the message area. First, remove the any other code you have in the guess function already.

If you look at the HTML for the page, you'll see that the the message area has an id of message-area. Update the guess function so that it finds the element for message-area and stores it in a variable called messageArea.

change the html for the message area

One you've found the message area and stored it in a variable called messageArea, it's easy to modify the HTML that's inside of the message area using JavaScript. Every HTML element allows you to modify the HTML by setting innerHTML equal to something. For example, this is how you would update the content for messageArea to say "hello!":

  messageArea.innerHTML = "hello!";

Update the guess function so that it uses the messageArea variable to change message area html to say "the guess button was clicked!".

If you've done everything correctly, you should see the message area quickly show your message, and then reload the page. The page is reloading, because the button you're clicking is automatically causing the form to reload the page. The way to fix this is to put return false; at the end of your function. Now, when you click the button, you'll see the message, but your page won't reload.

If you change the onclick on any elements that will cause the browser to take action, like a button or a link, you need to return false from the function that gets called when you click. This will tell the browser that you don't want the browser to follow the link or continue with what the button was supposed to do. Don't worry about why this works for now, just know that returning false will let you have full control over the event that you're trying to attach a function to.

Step 6

check the user's guess

The last thing we need to do is have the game check what the user's guess was. I've already created a function that returns the user's guess for you. It's called getUserNumber() and when you call it, you get the number that the user entered in the textbox before they hit the guess button.

check if the random number is higher than the user's guess

We want to give the user a message that tells them if their guess was lower or higher than the random number. We can use the comparison operators from last week to check the user's number versus the random number that the computer picked. For example, the following code will check if the number they user guess was higher and show them a message:

  if (randomNumber > getUserNumber())
  {
      messageArea.innerHTML = "It's higher!";
  }
  

The if statement compares the randomNumber variable to the value from getUserNumber() using the greater than operator. It's asking is randomNumber greater than getUserNumber's return value? And if the answer to that question is true, it's setting the HTML for messageArea to "It's higher!".

Right now, the code only checks if the number is higher. You can use another if statement to check if the random number is lower than the user's number. But, let's use an else if statement instead, so we can chain a few things together:

  if (randomNumber > getUserNumber())
  {
      messageArea.innerHTML = "It's higher!";
  }
  else if (randomNumber < getUserNumber())
  {
      messageArea.innerHTML = "It's lower!";
  }

Now, the code will also check if random number is lower and send the user a message that says "It's lower!" if it is. The code after the else if will only run if first if statement didn't run.

Finally, we can add an extra else statement that will tell the user that they guessed the number correctly. What would that code look like?

Assignment

Your assignment for this week is to complete the activity above and turn it in by Saturday, September 3rd at 10pm.