Introduction to JavaScript Fall 2009 Class 6

esse quam videri
Revision as of 23:09, 13 October 2009 by Matthew.ephraim (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Introduction

So far, we've been writing all of our JavaScript by hand. You may have noticed that some if it gets repetitive. Typing document.getElementById and giving all of the elements on your page ids might start to seem like a chore. Thankfully, there are ways to streamline the process of adding JavaScript to your page.

One thing that you can do to speed up your JavaScript development is use a JavaScript library. JavaScript libraries are collections of handy functions and tools that have been written by other people. When you include a JavaScript library on your page you can take advantage of the functionality that other people have written.

In this class, we will be mainly focusing on a library called jQuery. jQuery is an open source library that provides utlities for adding JavaScript event handlers to page elements and for manipulating HTML elements using JavaScript.

JavaScript Objects

One JavaScript feature that we haven't talked about is JavaScript Objects. jQuery uses JavaScript objects for a few functions, so you will need to understand them before taking of advantage of some of the functionality that jQuery provides.

Think of JavaScript objects as variables that contain other variables. Why would I want a variable that contained other variables? Sometimes, it's handy to group a set variables together under one variable. For example, let's say that I wanted to store some information about a person. I could create a variable for their first name, and their last name and their job title. Later on, I might want to create another variable for their hometown.

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

So far, I've created 4 variables for that one person. What if, instead, I could create one variable that just stored all of the information about a person. I can do exactly that using a JavaScript object.

First, I need to create a new object. I can create a new object for a person like this:

  var person = new Object();

new Object() will create a new object and store it in the person variable. Next, I want to store the person's information. Instead of creating a new variable for each piece of information, I can use the object like this:

  var person = new Object();
  person.firstName = "Matt";
  person.lastName = "Ephraim";
  person.jobTitle = "Programmer";
  person.hometown = "Cedar Falls";

Notice that, instead of creating a new variable, I'm using the person object instead. Every time I want to add a new piece of information I can say the name of the variable and then a dot (.) and then the name of piece of information I want to store. Later on, I can get the piece of information back by using the same name that I used when I set the piece of information, like this:

  alert(person.firstName); // alerts "Matt"
  alert(person.lastName); // alerts "Ephraim"
  alert(person.jobTitle); // alerts "Programmer"
  alert(person.hometown); // alerts "Cedar Falls"

It turns out, there are also some ways to shorten this process I little bit.

For example, this is the way I showed you how to create a new object before:

  var person = new Object();

I could have also said this:

  var person = {};

Using the two brackets is exactly the same as saying new Object().

If I wanted to, I could have also set all of the pieces of information at the same time that I was creating the variable, like this:

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

This piece of code does the exact same thing as creating the variable and setting each one of those pieces of information. The only difference is that the each item is set inside of the brackets. To create a new item (or property) I can add the name of the property, followed by a colon (:) and then the value of the property in quotes. Each property has to be separated by commas and a property has to be inside of the brackets.

Some of the jQuery functions use these kinds of objects to handle options that are passed into functions. I'll show you one of the functions later on. For now, pretend that the function alertPerson is a function that alerts the properties of a person. I could pass in the properties of a person like this:

  alertPerson({ firstName: "Matt", lastName: "Ephraim" });

Notice that I didn't need to create a new variable for the person. I can just pass in the information to the function and it figures out what to do with it.

jQuery

jQuery offers more functionality than I can cover in one class. This week I'll start out with some basic functionality that will get you started with using the library.

Including jQuery (or Other Libraries)

Before you can start using jQuery, or any other library that you want to use with your page, you will need to download and include the library code. jQuery can be downloaded from the jQuery homepage. Once you've downloaded the code and saved it to a file called jQuery.js (or whatever named makes the most sense to you), you can include the code on your page, just like you've been including the code so far. Say you downloaded the file, named it jQuery.js and stored it in your javascripts folder. To include it on your page, you'd simple add the following line to your code:

  <script src="javascript/jQuery.js" type="text/javascript"></script>

Make sure the script is included on your page before any of the scripts that take advantage of jQuery. Otherwise, your scripts won't be able to find jQuery and won't work.

Selectors with jQuery

One of the best features of jQuery is the ability to find elements on the page using CSS style syntax. So far, we've been finding elements like this:

  var element = document.getElementById("my-element");

This works fine, but it requires that we add ids to all of the elements that need are needed by the JavaScript. If we were using CSS we'd be able to use this syntax to find the element and add styles to it:

  #my-element { border: 1px solid black; }

With CSS we could also find elements by class:

  .with-border { border: 1px solid black }

Or we could even target child elements of other elements:

  ul#border-list li { border: 1px solid black; }

Which lets us find the child elements of certain elements on the page and apply special styles.

With JavaScript, these kinds of selectors take a lot of code to create. I haven't showed you how to do anything like that that yet, and, in reality, the complexities of creating code that worked that way would be more than one introductory course could cover. Thankfully, jQuery adds these kinds of selectors to JavaScript already.

So, back to finding our element with the id of my-element. With jQuery, we could simply say this:

  var element = jQuery('#my-element');

The jQuery function is a special function that takes in a CSS style selector and returns all of the elements that were that matched by that selector.

So, if I wanted to find all of the elements that had the class with-border I could make a jQuery call like this:

  var elements = jQuery('.with-border');

Or maybe I wanted to find all of the elements of the unordered list with the id border-list:

  var listItems = jQuery('ul#border-list li');

Notice how similar the selectors are to CSS? The idea is that any valid CSS selector should work with jQuery. So, you no longer have to worry about putting an id on every element of the page or about writing your own functions to figure out which elements should be modified with JavaScript.

See more on jQuery selectors here.

Events with jQuery

Once you've found an element or a list of elements with jQuery, you can start adding events to it. Events in jQuery work similarly to events in plain old JavaScript. One of the biggest differences, though, is that I can add multiple event handlers to one element. Let's say that I wanted to add a click handler to my-element. I could find it and attach an event with jQuery like this:

  function clickHandler() 
  {
      alert('hi');
  }
  
  var element = jQuery('#my-element');
  element.click(clickHandler);

Notice that, instead of setting onclick equal to clickHandler, we are passing clickHandler into a function called click. The reason that jQuery does it this way is because it allows you to add other handers if you wanted:

 function clickHandler() 
 {
     alert('hi');
 }
 
 function anotherHandler()
 {
     alert('another');
 }
 
 var element = jQuery('#my-element');
 element.click(clickHandler);
 element.click(anotherHandler);

In the example above there are two handler functions, and I've added them both to element using the click function that jQuery provides.

Another difference between regular JavaScript and jQuery is that the jQuery function doesn't just return one element, it returns all elements that match the selector you passed in. Let's say that you had an unordered list on your page like this:

  <ul id="myList">
     <li>Item</li>
     <li>Item</li>
     <li>Item</li>
  </ul>

The list has 3 items and you'd like each item to call a handler when the user mouses over the item. jQuery allows you to select all of the items and attach and event to all of them at once:

  var listItems = jQuery('#myList li');
  listItems.mouseOver(handlerFunction);

The selector #myList li finds all of the list items inside of the element with an id of myList. jQuery returns a collection of all of the list items. You can then add the event handlers the same way you'd add them to an individual item. In this case, the mouseOver function takes in a handler function that will be called whenever the user puts their mouse over any of the list items.

One other thing to note: just like when you attach an event handler to an event with regular JavaScript, event handlers attached with jQuery refer back to the element that the handler is tied to by using the this keyword (as you'll see below).

See more on jQuery events here

Changing Styles with jQuery

jQuery also has some tricks for changing the styling of elements. Above, we attached an event handler to all of the elements in this list:

  <ul id="myList">
     <li>Item</li>
     <li>Item</li>
     <li>Item</li>
  </ul>

Instead of attaching a generic eventHandler function, let's create a function called changeStyle that will change the style of each list item when it's clicked on. Attaching the event handler is simple:

  var listItems = jQuery('#myList li');
  listItems.click(changeStyle);

Now, we need to create a function called changeStyle. First, let's use the jQuery css function to directly modify the CSS styles of each list item:

  function changeStyle()
  {
      var element = jQuery(this);
      element.css({ background: "blue", border: "5px solid black"});
  }

There are a couple things going on with this function. First, we're passing this to the jQuery function. In this case, think of jQuery as a special wrapper that adds special features to an element. One of these special features the jQuery function adds is the css function. The css function takes in a JavaScript object that represents the CSS styles you'd like to add to the element. Notice that the syntax almost looks like regular CSS, except we're using it in JavaScript instead of a CSS file.

Adding CSS directly works fine, but we should be separating our presentation from our behavior. We can do this by defining the styles we'd like to add as classes in our JavaScript. We can then add the classes using jQuery.

In my CSS file:

  .list-style { background: blue; border: 5px solid black; }

In my JavaScript file:

  function changeStyle()
  {
      var element = jQuery(this);
      element.addClass('list-style');
  }

jQuery takes care of adding multiple classes, so you can add as many classes as you want:

  element.addClass('list-style');
  element.addClass('another-class');

Later, you can go back and remove classes as well:

  element.removeClass('list-style');

This is the preferred way of modifying the styles in your HTML, so try to avoid directly modifying the CSS styles of an object when you can.

See more on CSS manipulation with jQuery here.

jQuery Effects

jQuery offers a few built in functions for adding special effects to your page. These are pretty simple effects, but they can come in handy. There are additional effects that people have written that can be plugged in to jQuery, but, for now, we'll start with the simple built in ones.

Fading

Elements on your page can easily be faded in or faded out with jQuery:

  // Without a specified time
  element.fadeIn();
  element.fadeOut();
  
  // With a specified time
  element.fadeIn(1000);
  element.fadeOut(3000);

The the examples at the top fade the element in and out without specifying the amount of time it should take. The examples on the bottom are setting specific amount of time the effect should take. The effects functions take in the number of milleseconds an effect should take (there are 1000 milleseconds in one second).

See more on effects with jQuery here

Activity

Download the example jQuery files here. I will go over how each of the examples works and give you a chance to modify the scripts.

Assignment 3

Due Friday October 23rd at 11pm

Download the template files here and make the index.html page behave the way it is described. Be sure to use proper indentation and variable/function names and add comments to any functions or variables that might be unclear to others.

Post the files to your pub account and let me know when you have completed the assignment.

Feel free to email me at mephraim@colum.edu if you have any questions.