Navigation


Lesson: Introducing jQuery

Goals

Show how to add jQuery library. Binding functions to events. Form validation: Getting form data, changing HTML, changing styles, changing CSS.

Notes

jQuery is a bunch o' JS that John Resig wrote, and many others have contributed to. It's just plain JS, no executable or any such.

Including jQuery in your pages

Download the library from jquery.com. Get the latest stable version. It's all contained in one file, called something like jquery-1.3.2.min.js. There are lots of extensions for jQuery, called plugins. We'll use some later. But for now, let's stick with the basic library.

Save the jQuery file somewhere on your Web site, where your HTML files can get at it. I usually create a directory called lib or library or resources or some such, and put the file there.

In your HTML pages, you load the library like this:

<script type="text/javascript" src="lib/jquery-1.3.2.min.js"></script>

Now you can call jQuery in your JS code.

jQuery and the DOM

jQuery makes writing JS easier. In particular, it makes it easier to work with the DOM (document object model).

Here's a simple Web page. You can try it.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" 
                content="text/html; charset=iso-8859-1" />
        <title>Dogs</title>
    </head>
    <body>
        <h1>Dogs</h1>
        
        <p>Dogs are great! I love dogs. They're happy and playful and
        stuff. Well, most are. I like labs in particular. </p>
        
        <p>What is the name of your favorite dog?</p>
        
        <input type="text" id="dog_name">
        <button id="button_of_doom">Go</button>
        
    </body>
</html>

When you ask for this page (e.g., by typing its URL), your browser asks the server for it. The server sends the text above. The browser reads it in, and creates a tree-like structure in your computer's memory, representing the HTML. Then it renders (displays) the result.

You can inspect the DOM tree with the Firefox extensions Firebug and the DOM inspector. Here's what the inspector shows for part of the page:

DOM for the page

Here's what it looks like when rendered by a browser.

Page

You can see that there's a match between the HTML, the DOM, and the display. For example, there's an <h1> in the HTML, a DOM node for it, and something on the display.

You can use JS to change things in the DOM. This changes the display (or it can).

Let's change the page:

<style type="text/css">
    .big_bold {
        font-size: 32px;
        font-weight: bold;
        color: red;
    }
</style>
...
<p>
    Dogs are great! I love dogs. They're happy and playful and
    stuff. Well, most are. I like 
    <span id="labs">labs</span> in particular.
</p>

You can see it here. The <span> didn't change the look of the page (neither did the style, because we haven't use it yet). But it did change the page's DOM representation:

DOM for the new page

I've given the <span> an id of labs. "id" is an attribute of the <span>. The id does not affect the way the <span> element is rendered. But I can use it to refer to the <span> in JS code. Then I can write code that changes attributes of the <span>. Those changes can affect the way the element is displayed.

For example, I could write this JS code:

$('#labs').addClass('big_bold');

The first part, $('#labs'), tells JS to find the element with an id of labs. The rest of the statement adds the class big_bold to it. The page will change, looking like this:

Style applied

I could have done the same by changing the HTML to:

<span id="labs" class="big_bold">labs</span>

So, what's the big deal? Well, the difference is that with my JS code, I can control when the change occurs. For this to make sense, we need to look at events.

Binding functions to events

An event is something that happens to some DOM object. For example, when the user clicks on a button, there is a click() event on that button. When the user types a character into a text field, there is a keypress() event on the field.

Most events happen in response to user actions, but not all. For example, when the HTML document is finished loading, it triggers a ready() event.

The key is: you can tie JS code to events. When the event happens, the code runs.

Let's change the HTML page. You can try it here.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Dogs</title>
        <style type="text/css">
            .big_bold {
                font-size: 32px;
                font-weight: bold;
                color: red;
            }
        </style>
    <script type="text/javascript" src="lib/jquery-1.3.2.min.js"></script>  1 
    <script type="text/javascript">
        $(document).ready( function() {   2 
            //This code executes when the document is loaded and ready to display.
            //Set up a click handler for the heading.
            $('h1').click(function(){   3 
                $('#labs').addClass('big_bold');   4 
            }); 
        });
    </script>
    </head>
    <body>
        <h1>Dogs</h1>
        
        <p>
            Dogs are great! I love dogs. They're happy and playful and
            stuff. Well, most are. I like 
            <span id="labs">labs</span>  5  in particular.
        </p>
        
        <p>What is the name of your favorite dog?</p>
        
        <input type="text" id="dog_name">
        <button id="button_of_doom">Go</button>
        
    </body>
</html>

The jQuery library is included in the page at 1. At 2, some code is run when the browser has finished loading the document. Technically, ready() is a method of the document object. But if you call it a function, that's OK.

At 3, the program attaches code to the click event of the <h1>. The code $('h1') tells JS to find all the h1 elements. There is only one on this page, but if there had been more, they all would have been returned.

The code to attach to the event is at 4. It finds all of the elements that have an id of "labs." That's what the # means in $('#labs') - inspect the id attribute of the elements on the page. ids should be unique, that is, in a correct HTML page, only one element should have an id of "labs."

The code adds a class to the element. The element is at 5.

Exercise 1. Be alert. (We need all the lerts we can get.)

Change the code to this:

$(document).ready( function() {
    alert('Start document ready');
    $('h1').click(function(){
        alert('Start h1 click');
        $('#labs').addClass('big_bold');
        alert('End h1 click');
    }); 
    alert('End document ready');
});

Notice what happens when you load the page and run the program.

alert()s are a good way to figure out how a program is working. Or is not working. Cut-and-paste this code:

$(document).ready( function() {
    alert('Start document ready');
    $('h1').clck(function(){
        alert('Start h1 click');
        $('#labs').addClass('big_bold');
        alert('End h1 click');
    }); 
    alert('End document ready');
});

What happens?

With the alert()s, you can tell when something bad is happening. That way, you know where to look for problems.

Get used to doing this! You will make mistakes in your code. This technique will save you much frustration.

Now change this:

$('h1').click(function(){

to this:

$('p').click(function(){

What happened? Why?

Change the click code to this:

if ($('#labs').hasClass('big_bold')) {
    $('#labs').removeClass('big_bold');
}
else {
    $('#labs').addClass('big_bold');
}

What happens now?

Getting/setting form data

You can get the contents of a form field, like this:

n = $('#dog_name').val();

Question: what does $('#dog_name') refer to?

You can store the value in a variable (like the statement above), or output it with an alert(), or whatever.

You can set the value of a form field like this:

$('#dog_name').val('a name');

Exercise 2. Name of the dog.

Change the dog page so that the form field has the word Oscar in it when the page is loaded. Use jQuery.

Solution - try it yourself first.

Changing page content

You can change the content of an element. For example, suppose we added this to the dog page:

<p>Your favorite dog is <span id="fave"></span>.</p>

Now put this in ready():

$('#button_of_doom').click(function() {
    n = $('#dog_name').val();   1 
    $('#fave').html(n);   2 
});

1 gets the value of the field, and puts it into the variable n. 2 sets the contents of the element "fave." Give it a try.

This could be done in one step, like this:

$('#button_of_doom').click(function() {
    $('#fave').html( $('#dog_name').val() );
});

Either way is fine, though for a beginner, the first one might be easier to understand.

Exercise 3. Check, check, check...

Change the code for the button so that it does this:

  • Get the value in the field.
  • If the value is empty, use alert() to tell the user s/he must enter a value.
  • If the value if not empty, show it in fave.

Solution - try it yourself first.

Showing and hiding stuff

The is what the solution to exercise 3 looks like when the page is loaded.

Thing to hide

"Your favorite dog is ." looks a little strange. Maybe we should hide it, so that it only appears when the user has typed a name and pressed Go.

Let's change the favorite dog tag to this:

<p id="fave_container">Your favorite dog is <span id="fave"></span>.</p>

I've added an id to the element I want to hide and show. I called it fave_container, because it contains the element fave.

In the page's CSS, I'll add the following, to hide the container when the page first loads.

#fave_container {
    display: none;
}

Now I'll change the button code to this:

$('#button_of_doom').click(function() {
    n = $('#dog_name').val();
    if (n == '') {
        alert('Please enter the name of a dog.');
    }
    else {
        $('#fave').html(n);
        $('#fave_container').show();   1 
    }   
});

1 shows the container element. You can try it here.

Try giving a parameter to show, like show('slow'). Ooo, cool, isn't it?

You can use elements like this for error messages. The message is hidden until the user does something wrong, and then it appears.

Focus, focus!

Try the last example again. When the page first loads, you have to click in the dog name field before you can type. This is called moving the focus to the field. It would be more convenient for the user if the focus was on the dog name field as soon as the page was loaded, so s/he could just start typing.

Add this to ready():

$('#dog_name').focus();

Now reload the page. As you can see, the focus is in dog_name. The user is ready to type.

Exercises

Exercise 4. Hypotenuse length

Write a page to compute the length of the hypotenuse of a right triangle from the length of the other two sides.

Hypotenuse
From Wikipedia

The formula in JS is:

hyp = Math.sqrt(c1*c1 + c2*c2);

You can assume that the user makes no errors in entering the data.

Solution. Try it yourself before you look at the code.

Exercise 5. Hypotenuse length with error checking

Add error checking to your program. Hint:

if ( c1 == '' || isNaN(c1) ) {

Solution. Try it yourself before you look at the code.

Exercise 6. Note taker.

Write a page that has a <textarea> on it. When the user types something in the <textarea> and clicks a button, the text that the user typed gets attached to the notes area.

Note taker

Solution. Try it yourself before you look at the code.