Introduction to JavaScript Fall 2009 Class 7

esse quam videri
Jump to: navigation, search

Introduction

Last week, I introduced you to jQuery and showed you how to use it to add classes, event handlers and effects to your HTML. This week I want to help you rewrite the lock game that we wrote for Class 5. We're going to use the same template, but this time we'll use jQuery to make the game work.

Before things get too much more complicated, I also want to show you how you can start to organize your code a little bit more. One simple way is to use JavaScript objects to organize parts of your code that are related to each other.

Using Obects to Organize Your Code

Last week, I showed you how to create JavaScript objects to organize pieces of code that are related to each other. For example, I showed you a group of related variables like this:

  var firstName = "Matt";
  var lastName = "Ephraim";
  var jobTitle = "Programmer";
  var hometown = "Cedar Falls";

I also showed you that the variables could be organized into a person object:

  var person = {};
  person.firstName = "Matt";
  person.lastName = "Ephraim";
  person.jobTitle = "Programmer";
  person.hometown = "Cedar Falls";

Each variable related to the person is now stored as a property of the person object. This makes it easy to reference information about the person later on:

  // Alert the person's full name
  alert('The person's name is ' + person.firstName + " " + person.lastName);

Objects can be used to store all kinds of information, including strings, numbers and even functions. A few weeks ago, we created a combination lock that had a variable for a combination, a variable that deterimined if the lock was unlocked or not and some functions that made the lock actually work. The code we wrote worked fine, but if we would have written more code, it might have gotten a little bit confusing. What if we needed a few different variables called COMBINATION, or what if we needed 2 functions called reset? Both of these issues could be addressed by storing the code related to the lock in an object, instead of just using regular variables.

To start organizing the code, we need to create a new object to store all of the functions and variables related to the lock. Let's call the object Lock:

  var Lock = {};

Lock is now an empty object, ready to have properties stored on it. To start with, we can store the lock's combination as a propery of the Lock object:

  var Lock = {};
  Lock.COMBINATION = '111';

Later, the lock's combination can be referenced like so:

  alert(Lock.COMBINATION);

We can also stored the unlocked variable as a property on the lock, as well:

  Lock.unlocked = false;

Later, the value can be changed or checked:

  if(Lock.unlocked) 
  {
      // do something
  }
  
  Lock.unlocked = true;

Now that we have the variables stored as properties on the Lock object, instead of just as regular variables, we could have other objects that had COMBINATION or unlocked properies and use them somewhere else in our code:

  var BikeLock = {};
  BikeLock.COMBINATION = "5555";
  BikeLock.unlocked = false;
  
  if (BikeLock.unlocked)
  {
      // ride the bike
  }

One thing that I haven't talked about yet is how you can save functions as variables or as properties. So far, the way we've created functions has looked like this:

  function reset()
  {
      // some code to reset the lock
  }

JavaScript also lets you create functions like this:

 var reset = function()
 {
    // some code to reset the lock  
 };

Notice that we are now creating a variable called reset and storing a function in the variable. Instead of giving the function a name right away, you can leave the name off of the function and create a variable that stores the function instead. Both ways of creating the function will work the same. Whichever way you use, you always be able to call the function like this:

  reset();

Additionally, you can store a function on an object. Just like you can store a regular variable on an object. Storing the reset function on the Lock object looks like this:

  Lock.reset = function()
  {
      // some code to reset the lock
  }

Later, to call the function, you would say:

  Lock.reset();

The function would work the same, no matter how you created it. Using an object to store your code is just the first step toward organizing your code in a better way.

Modifying HTML and attributes with jQuery

Last week, I introduced you to the basics of jQuery. There are still many other features of jQuery to cover, but some of the most useful features are related to modifying an element's HTML and an element's attributes.


Modifying HTML

First, let me show you how to read and modify and element's HTML with jQuery. We've done this before in a few earlier classes and the code looked something like this:

  var element = document.getElementById("#myElement");
  element.innerHTML = "Some text";

The method we've used already works fine, but jQuery allows us to streamline that code a little bit by using the html function:

  var element = jQuery("#myElement");
  element.html("Hello");

Later, we can read back the element's html using the same function, but without passing in some HTML:

  var element = jQuery("#myElement");
  var html = element.html();

When the html function is called without passing in any HTML to be used on the element, it simply returns the HTML that is currently inside of the element, the same as innerHTML would if we were using JavaScript without jQuery.

Modifying Attributes

Some HTML elements rely on their attributes to display in special ways. For example, the img tag relies on the src attribute to determine the path to the image that should be displayed by the tag. The img tag also relies on the alt attribute to give the image some alternative text if the actual image file couldn't be loaded. So, for example, let's say we had a picture of a duck:

  <img id="animal.jpg" src="duck.jpg" alt="A picture of a duck" />

Currently, the img tag displays a picture of a duck. We can use the jQuery attr function to change the image's attributes:

  var image = jQuery("#animal");
  image.attr({ src: "chicken.jpg", alt: "A picture of a chicken" });

The attr (for attributes) function takes in an object that represents a collection of attributes to change for the age. In the example above, the code is chaning the src attribute and the alt attribute. If we wanted to read back an attribute we can use the attr function, but this time, we just need to pass in the name of the attribute we want to check:

   var image = jQuery("#animal");
   var imageSrc = image.attr("src");
   var imageAlt = image.attr("alt");

If you pass in the name of an attribute to the attr function, it will return the current value of the attribute that matches the name you passed in.

Activity 1

The first activity today involves the same lock game that we worked on during Class 5. This time, however, we're going to rewrite the code for the lock and use jQuery.

I will walk you through each step and how you how jQuery can make things a little more streamlined. You can find the template for the game here.

You may also want to look at the solution for the orignal lock as reference.

A few things to think about:

  • Selectors

Remember that you can use jQuery's selectors to find the elements, instead of just finding them by their id. For example, you can find all of the number boxes by using their class name. So a jQuery selector for all of the number boxes would look something like this:

  var numbers = jQuery('.number');

You can then attach event handlers or modify styles using the numbers variable, which represents a collection of all of the number boxes that were found.

  • Adding classes

You can add classes or remove classes for an element by using the addClass and removeClass functions:

  var element = jQuery('#id');
  element.addClass('highlighted');
  element.removeClass('highlighted');

Activity 2

For this activity we will be organizing our code a bit by keeping all of our functions and variables as properties of an object, instead of as regular variables. We will call this object Lock. You can get started by creating a Lock object at the beginning of your code:

  var Lock = {};

Then, once you have the empty object, you can start adding variables and functions to it:

  // Store the combination on the lock
  Lock.COMBINATION = "111";
  
  // Store the reset function
  Lock.reset = function() 
  {
     // code for the reset function
  }
  

You should only need to store variables that might be useful for all of your functions on the Lock object. If you're creating a variable inside of a function, don't worry about storing it on the Lock object. Just focus on variables like COMBINATION and unlocked that are declared outside of functions.

Completed Lock Code

This is the completed code from both of the activities that we did in class 7: Completed Lock Code

Assignment 4

Due Friday October 30th at 10pm

Take the code that you created for Assignment 3 and organize it by storing any common variables in an object.

My advice is to create an object called Behavior, similar to the Lock object we created for Activity 1. Then, start storing your functions one at a time on the Behavior object. Once your functions are working, store any variables that are declared outside of your functions on the Behavior object.

As an example, suppose you had a function called changeSize. That function should be stored on the Behavior object, so that you can call it like this:

 Bevavior.changeSize();

Instead of calling it like this:

  changeSize();

See the solution code for Activity 4 for an example of how code that's organized with an object should look.

Assignment 3

Remember that assignment 3 is due this Friday