Requirements

 

Prerequisite knowledge

An understanding of CSS and basic JavaScript concepts.

Article: Introduction to JavaScript

jQuery: Download

User level

Beginning

Required products

Dreamweaver (Download trial)

 

Sample files

Adding interactivity to web pages has been dramatically simplified thanks to jQuery, the most popular JavaScript framework. The reasons for jQuery's popularity can be summarized as follows:
 
  • You write less code—what would take 20 lines or more of JavaScript can be achieved in just two or three lines of jQuery.
  • The same code runs in all browsers—there's no need to write special code for Internet Explorer.
  • It uses CSS selectors, leveraging knowledge that most web designers already have.
Dreamweaver CS5.5 now has full code hinting for jQuery, making it even easier to use.
 
This tutorial introduces you to the basics of jQuery.
 
Note: The instructions assume you are using Dreamweaver CS5.5. You can follow the tutorial with any version of Dreamweaver or a text editor, but you won't have the benefit of code hints. Just copy the finished code instead.
 

 
What is jQuery?

According to the jQuery website, "jQuery is designed to change the way that you write JavaScript." Not only has it done that, it has achieved something even more impressive—it has encouraged vast numbers of web designers to start writing their own JavaScript instead of copying and pasting code from often dubious sources. jQuery is what's known as a JavaScript library, but it's not the sort of library that's packed with rows and rows of books. It's a relatively small file (84 KB uncompressed) that contains dozens of JavaScript functions (methods) designed to simplify working with JavaScript. You simply link the file to your web pages and use the jQuery methods to add interactivity to your site.
 
JavaScript is a powerful language, but there are two major barriers to its use:
 
  • JavaScript was originally developed by Netscape, Microsoft Internet Explorer's arch rival during the browser wars of the 1990s. Although Internet Explorer quickly adopted the language (its version is officially called JScript), there are fundamental differences in certain areas, such as event handling. Writing scripts that work in all browsers often involves writing twice as much code.
  • Interactivity involves adding and removing page elements, or affecting the styles applied to them. The official methods of doing so, using the World Wide Web Consortium's Document Object Model (W3C DOM), are cumbersome.
JavaScript libraries aimed at solving these two problems started to emerge around 2005. The first to gain widespread use were Prototype and script.aculo.us. Other well-known JavaScript libraries include the Dojo Toolkit, Moo Tools, the Yahoo! UI Library, and the Adobe Spry framework. All have the same basic aims as jQuery: to provide cross-browser tools for adding interactivity to pages. So, why should you choose jQuery in preference to the others?
 
  • jQuery works in all current browsers, including Internet Explorer 6+, Firefox 2+, Safari 3+, Chrome, and Opera 9+.
  • It's free, open source code dual-licensed under the MIT License and GNU General Public License.
  • It's estimated that three out of every four websites that use a JavaScript library have adopted jQuery.
  • Leading companies that use jQuery include Amazon.com, Bank of America, BBC, and Twitter.
  • Oh yes. . . It's relatively easy to learn.
Adobe has become an official sponsor of jQuery Mobile, a new framework for developing mobile applications, which is based on the jQuery core library; and Dreamweaver engineers have been actively contributing code to the project.
 
How to get jQuery
 
Although Dreamweaver CS5.5 has full code hinting for jQuery, you need to link your web pages to the jQuery core library. There are two ways to do so:
 
  • Link to the latest version of the library hosted on a content distribution network (CDN).
  • Download a copy of the library and store it with the files in your own site.
Details of both methods can be found at jQuery docs.
 
For the purposes of this tutorial, I recommend that you work with a local version of the jQuery library. The example files contain a copy of jQuery 1.5.2, which was the current version at the time this tutorial was written. Replace this library with a more up-to-date version from the jQuery site if one is available.
 
Note: The download page of the jQuery site has links for minified and uncompressed versions. They both contain the same code, but the minified version has all the whitespace removed, resulting in a smaller file. When you click the download link, the file normally opens in your browser window. Select File > Save As to save the file to your local hard disk.
 
Preparing the tutorial files
 
If you haven't already done so, download jquery.zip and unzip the sample files that accompany this tutorial. All the files for the tutorial are in a folder called jqtut. Create a new Dreamweaver site with the jqtut folder as the site root. Alternatively, copy the jqtut folder to an existing Dreamweaver site, and work within that folder.
 

 
Linking and initializing jQuery

For many years, the recommended practice has been to attach external JavaScript files in the <head> of a web page. However, all the code in a JavaScript file needs to be processed before the rest of the page can continue loading. Consequently, it's now recommended to attach external JavaScript files just before the closing </body> tag unless the page depends on the code being loaded earlier. Doing so results in faster loading pages.
 
  1. Open jq_01.html in the jqtut sample file folder, and switch to Code view or Split view.
  2. Position the insertion point immediately before the closing </body> tag, and click Script in the Common category of the Insert panel/bar, or select Insert > HTML > Script Objects > Script.
  3. In the Script dialog box, click the folder icon on the right of the Source text field, navigate to the js folder, and select jquery-1.5.2.min.js. If you have downloaded a more recent version of jQuery, select that instead. Click OK. The filename should now be listed in the Script dialog box, as shown in Figure 1.
Figure 1. Select the jQuery library file.
Figure 1. Select the jQuery library file.

 

  1. Click OK to close the Script dialog box. The jQuery library should now be linked to your page just before the closing </body> tag, as shown in Figure 2.
Figure 2. The recommended location for the jQuery library is just before the closing tag.

 

  1. Save the page.
Adding the jQuery library to a page doesn't do anything on its own. It simply makes the jQuery methods available to your own scripts, which must always come after you have attached the jQuery library.
 
Creating a document-ready handler
 
Before you can start interacting dynamically with a web page, the browser needs to load the HTML and build the tree structure of the DOM. Traditionally, JavaScript has used the onload event handler to initialize scripts. However, this waits for all the page's resources, including images, to finish loading before doing anything. To speed up this process, jQuery uses its own document ready handler.
 
There are several ways of creating the document ready handler, but for this tutorial, I'm going to show you only the shorthand version. It's the simplest and most commonly used.
 
  1. Continue working with the same file as before. Alternatively, use jq_02.html.
  2. Insert several new lines between the <script> element that you inserted in the previous exercise and the closing </body> tag.
  3. Add a pair of opening and closing <script> tags in the space you just created.
  4. Inside the new <script> block, type $(function() {.
     
  5. Press Enter/Return twice to add two new lines. Then type a closing curly brace, followed by a closing parenthesis and a semicolon. The two <script> blocks at the bottom of your page should now look like this:
<script type="text/javascript" src="js/jquery-1.5.2.min.js"></script> <script> $(function() { }); </script>
All JavaScript code that you want to run as soon as the page loads needs to go between the curly braces of the document ready handler.
 
Saving the jQuery document ready handler as a snippet
 
The jQuery document ready handler is a piece of code that you use all the time with jQuery, so it's worth saving as a snippet.
 
  1. Select the document-ready handler that you created in the previous exercise, including the opening and closing <script> tags.
  2. Right-click and select Create New Snippet from the context menu.
  3. Type jQuery Document Ready Handler in the Name field of the Snippet dialog box.
  4. Dreamweaver copies the selected code into the "Insert before" pane.
  5. Click inside the blank line, select the remaining code, and cut it to your clipboard.
  6. Paste the code into the "Insert after" pane. The Snippet panel should look like Figure 3.
Figure 3. The jQuery document ready handler is used so often, it's worth saving it as a snippet.

 

  1. Click OK to save the snippet.
Whenever you need to insert a <script> block with a jQuery document-ready handler, just put the insertion point where you want to add the block, and double-click the snippet in the Snippets panel.
 

 
Adding a new paragraph dynamically

To demonstrate how jQuery works, this exercise adds a new paragraph dynamically to the page when it loads. Admittedly, it's not the most practical use of jQuery, but it illustrates two essential features: selecting page elements and using jQuery methods.
 
  1. Continue working with the same file as before. Alternatively, use jq_02.html.
  2. On the blank line inside the document ready handler, type a dollar sign followed by an opening parenthesis. Dreamweaver CS5.5 jQuery code hints spring into action (see Figure 4).
Figure 4. Dreamweaver offers jQuery code hints as you type.

 

  1. The first two code hints are for document, which applies to the whole document, and this, which applies to the event target. Neither is appropriate for this exercise, so type a quotation mark (single or double—it doesn't matter).
    Dreamweaver automatically adds a matching closing quotation mark and displays a list of code hints for HTML elements (see Figure 5).
     
Figure 5. When you type a quotation mark, the code hints display HTML elements.

 

  1. You want to select the <body> tag, so type bo and press Enter/Return. Dreamweaver completes the tag name and leaves the insertion point inside the closing quote. jQuery uses CSS selectors to select page elements, so Dreamweaver can't tell if you're going to refine the selector. In this case, you have finished. Move the insertion point to the right of the closing quote, and type a closing parenthesis. The code in the document ready handler now looks like this:
$(function() { $('body') });
    This is how jQuery selects the <body> element of the page.
     
  1. After selecting one or more page elements, you can apply jQuery methods to them. To append new HTML elements to selected elements, you use the append() method, passing the new elements as an argument.
    Type a dot (or period) after $('body'). Dreamweaver CS5.5 brings up code hints for all the jQuery methods that can be applied to the selected element(s). Select the append() method, and pass it a string of HTML like this:
     
$(function() { $('body').append('<p>This paragraph was added dynamically.</p>'); });
  1. Save the page and view it in a browser or Live view. The new paragraph is added to the page (see Figure 6).
Figure 6. The HTML passed as an argument to append() is added to the page.

 

You can check your code, if necessary, with jq_03.html.
 
By way of comparison, dom_01.html in the sample files produces the same result using standard JavaScript and the element creation methods recommended by the W3C DOM. The <script> block in the <head> section of the page looks like this:
 
<script> function addPara(text) { var body = document.getElementsByTagName('body')[0], p = document.createElement('p'), content = document.createTextNode(text); p.appendChild(content); body.appendChild(p); } window.onload = function() { addPara('This paragraph has been added dynamically.'); }; </script>
I think you'll agree that the jQuery way of doing it is much simpler and easier to understand. However, don't think of using jQuery as somehow cheating. What jQuery is doing in the background is using standard JavaScript. It's just hiding the complexity and helping preserve your sanity.
 

 
Chaining jQuery methods

One of the biggest time-saving features of jQuery is the ability to chain methods. What this means is that you can apply multiple methods to the same selected element(s) using dot notation. A simple example shows how this works.
 
  1. Continue working with the same file as before. Alternatively, use jq_03.html.
  2. Put the insertion point just before the semicolon at the end of the line of code in the jQuery document ready handler, and press Enter/Return to insert a new line.
  3. To keep the code tidy, insert several spaces to align the insertion point with the dot after $('body') on the preceding line. Then type a dot. Dreamweaver brings up the code hints for jQuery methods again.
  4. Select addClass from the code hints. This inserts the method name followed by an opening parenthesis.
  5. Type a quotation mark. Dreamweaver knows that the addClass() method expects the name of a CSS class, and it detects a class called reverse in the style sheet attached to the page. So, it offers a code hint for the class (see Figure 7). If there were more classes, the hints would list all of them alphabetically.
Figure 7. The jQuery code hints detect classes in the page's style sheet.

 

  1. Select the reverse class and add a closing parenthesis. The code in the document-ready handler now looks like this:
$(function() { $('body').append('<p>This paragraph was added dynamically.</p>') .addClass('reverse'); });
  1. Save the page and test it in a browser or Live view. As well as adding the second paragraph, the jQuery script now applies the reverse class to the <body>, changing the background color to black and the text color to white (see Figure 8).
Figure 8. Both jQuery methods have been applied to the of the page.

 

You can check your code, if necessary, with jq_04.html.
 
You can chain as many methods as you like to the selected element(s). It's not necessary to put each one on a new line as shown in this example. You can chain them in a single line, but breaking up the code like this makes it easier to read and maintain.
 

 
Binding event handlers to elements

The examples in the Introduction to JavaScript <link to tutorial> tutorial use the onClick attribute to bind an event handler function to a link. This is the traditional way to bind event handlers to an element. However, it limits you to a single event handler and clutters your HTML code with behavioral markup. The modern approach is similar to CSS in that events are bound dynamically to page elements rather than embedded in the HTML. Unfortunately, Internet Explorer uses a different event model from other browsers, complicating the necessary code. jQuery cuts through this problem with a simple, cross-browser solution.
 
Showing and hiding HTML elements
 
The next exercise shows how to bind click events to a series of <h2> elements to toggle open and closed the paragraph following each heading. It introduces the concept of anonymous functions, which are widely used in jQuery. An anonymous function is identical to an ordinary function, apart from the fact that it doesn't have a name.
 
  1. Open jq_05.html. The page contains three <h2> headings, each followed by a single paragraph.
  2. In Code view, attach the jQuery library and create a jQuery document-ready event handler in the same way as in the first exercise.
  3. Inside the jQuery document-ready event handler, create a jQuery selector for the paragraphs following <h2> headings, using the adjacent sibling combinator (h2 + p) like this:
$(function() { $('h2 + p') });
    This selects the first paragraph following an <h2> heading. There are three headings on the page, so it selects  the paragraph following each heading.
     
  1. Apply the hide() method to the selector like this:
$(function() { $('h2 + p').hide(); });
    This hides the three paragraphs when the page loads (Figure 9).
     
Figure 9. The paragraphs are hidden dynamically.
    Using jQuery to hide the paragraphs, rather than setting the display property to none, means that the text remains accessible in browsers that have JavaScript turned off.
     
  1. On the next line, type $('h2') to create a jQuery selector for the <h2> headings. Then type a dot to apply a jQuery method to the selected elements. You want to add a click event to the headings. Type cli. In Dreamweaver CS5.5, this displays the code hints for the click() method. As Figure 10 shows, you have three options.
Figure 10. Dreamweaver displays several options for the click() method.

 

    The first option simply inserts click() and leaves you to add whatever code you want. The second option inserts click followed by an opening parenthesis, again leaving you to add the rest of the code. The third option automatically inserts an anonymous function. It's this third option that you want. Select it and press Enter/Return. The code now looks like this:
     
$(function() { $('h2 + p').hide(); $('h2').click(function(e) { }); });
  1. Inside the anonymous function, you build the code that you want to be executed when the event target—one of the <h2> headings—is clicked. The selector that refers to the event target in jQuery is $(this). You need to select the paragraph that immediately follows the heading that has been clicked. Conveniently, jQuery provides the next() method, which takes as its argument a string containing the name of the HTML element you want to select. And to toggle between showing and hiding an element, jQuery provides a method called—you've guessed it—toggle(). When you put it all together, the code looks like this:
$(function() { $('h2 + p').hide(); $('h2').click(function(e) { $(this).next('p').toggle(); }); });
  1. Save the page and test it in a browser or Live view. When you click one of the headings, it pops open, moving the remaining content down the page (see Figure 11). Clicking the same heading hides the paragraph again. Each heading and its related paragraph work independently of the others—all thanks to just a few lines of jQuery.
Figure 11. When you click a heading, it toggles the following paragraph open or shut.
 
You can check your code, if necessary, against jq_06.html. Keep your file open, because you'll improve it in the next exercise.
 
The toggle() method is handy for elements that you want to toggle open and shut. As you might expect, in addition to hide(), jQuery also has a dedicated method called show(). In effect, all three methods  change the CSS display property of the selected element(s) to block or none.
 
Changing CSS properties dynamically
 
Although the anonymous function you created in the preceding exercise toggles the display of the paragraphs, the effect needs to be refined. The mouse pointer needs to indicate that the headings are clickable, and the arrows alongside each heading should flip down when the related paragraph is displayed. Let's fix those items.
 
  1. Continue working with the same page as before. Alternatively, use jq_06.html.
  2. To change the cursor to a hand pointer, you need to chain the css() method after the click() method. This is where an understanding of JavaScript syntax is essential when working with jQuery. Put the insertion point after the click() method's closing parenthesis. Use Figure 12 as a guide if you're not sure where it is.
Figure 12. When chaining methods, you need to find the correct location.

 

  1. Press Enter/Return to insert a new line. Then type a dot followed by css('cursor', 'pointer'). Dreamweaver CS5.5 continues providing code hints as you type.
    The css() method takes two arguments: the name of the property and the value you want to assign to it. The code now looks like this:
     
$(function() { $('h2 + p').hide(); $('h2').click(function(e) { $(this).next('p').toggle(); }) .css('cursor', 'pointer'); });
  1. If you save the page and test it now, you'll see that the cursor now indicates that the headings are clickable.
  2. The next task is to fix the headings' background images. To do so, you need to refer to the next paragraph again inside the anonymous function. When you need to refer to the same selection more than once, it's good practice to store the selection as a variable. Amend the code like this:
$(function() { $('h2 + p').hide(); $('h2').click(function(e) { var para = $(this).next('p'); para.toggle(); }) .css('cursor', 'pointer'); });
    This saves a reference to $(this).next('p') as para, and then applies the toggle() method to para. The effect is the same as before.
     
  1. To change the background images, you need to create a condition that checks the display property of the subsequent paragraph. In step 3, you used the css() method with two arguments to set a CSS property. Using the method with just the property name as an argument gets the value of the property. So, the final version of the code looks like this:
$(function() { $('h2 + p').hide(); $('h2').click(function(e) { var para = $(this).next('p'); para.toggle(); if (para.css('display') == 'none') { $(this).css('background-image', 'url(images/arrow-r.png)'); } else { $(this).css('background-image', 'url(images/arrow-down.png)'); } }) .css('cursor', 'pointer'); });
    The condition checks the value of the paragraph's display property. If it's none, the paragraph is hidden. So, the code inside the first conditional block uses the css() method with two arguments to set the background-image property of the event target (the <h2> heading that was clicked). It's important to note that the url() value is relative to the current document, not to the style sheet. Dreamweaver CS5.5 helps you get the correct path through code hints. If the paragraph is hidden, arrow-r.png is used as the background image. Otherwise, arrow-down.png is used.
     
  1. Save the page, and test it in a browser or Live view. As Figure 13 shows, the mouse pointer is converted to a hand when hovered over one of the headings, and the arrow flips down when an item is opened.
Figure 13. The heading and arrow now respond to the user's interaction.

 

You can check your code, if necessary, against jq_07.html.
 
As you have just seen, jQuery methods often perform different, but related roles when used with a different number of arguments. The css() method follows a common pattern. When used with a CSS property as a single argument, it gets the property's value. But when a second argument is supplied, it sets the value of the specified property. The attr() argument performs the same getter/setter role for the attributes of an HTML element.
 

 
Passing arguments to event handlers

In the previous tutorial, Introduction to JavaScript, the changeFontSize() function takes as its argument the ID of the element you want to affect like this:
 
onClick="changeFontSize('fruits')"
You can't do this with jQuery event handlers. Instead, you use a data object to handle the arguments.
 
In simple terms, you create a JavaScript object with a comma-separated series of name/value pairs in a pair of curly braces. Each name and its associated value are separated by a colon. For example:
 
var boy = { name: 'Peter Pan', home: 'Neverland', age: 'forever young' };
Each name is a property of the object. So, the value of boy.name is "Peter Pan" and boy.age is "forever young."
 
The following exercise shows how to adapt the changeFontSize() function from the Introduction to JavaScript tutorial for use with jQuery. In the original version, the function takes the ID of an element as an argument. The jQuery version takes the event object as its argument, and the ID is transmitted to the function through a data object.
 
  1. Open jq_08.html in Code view. This is a copy of the final version of the exercise files from the Introduction to JavaScript tutorial. If you load the page into a browser and repeatedly click the "Change list font size" link, the font size increases in steps from 16px to 24px and then reverts to 16px.
  2. Put the insertion point just before the closing </body> tag, and attach the jQuery library and insert a jQuery document ready event handler as in the previous exercises.
  3. In the <head> of the page, select the changeFontSize() function definition (without the surrounding <script> tags) and cut it to your clipboard.
  4. Delete the <script> tags from the <head>, and paste the function definition inside the jQuery document ready event handler. The <script> block at the bottom of the page should look like this:
<script> $(function() { function changeFontSize(id) { var list = document.getElementById(id), fontSize = list.style.fontSize, sizes = [16, 20, 24, 28], len = sizes.length, i; if (!fontSize) { list.style.fontSize = sizes[1] + 'px'; } else { for (i = 0; i < len; i++) { if (i == len - 1) { list.style.fontSize = sizes[0] + 'px'; } else if (fontSize == sizes[i] + 'px'){ list.style.fontSize = sizes[i + 1] + 'px'; break; } } } } }); </script>
  1. Remove the link from the "Change link font size" paragraph, and give the paragraph the ID trigger like this:
<p id="trigger">Change list font size.</p>
  1. Add a <style> block in the <head> of the page to set the display property of trigger to none:
<style> #trigger { display:none; } </style>
  1. If you load the page into a browser now, the paragraph is no longer displayed. This is how the page appears to anyone visiting the page with JavaScript disabled. Hiding the link allows you to display it only when JavaScript is enabled.
  2. When JavaScript is enabled, you want the paragraph to be displayed and look clickable when the mouse pointer hovers over it. Add the following code to the document-ready handler—it doesn't matter whether it goes before or after the changeFontSize() function definition:
$('#trigger').show() .css('cursor', 'pointer');
  1. You now need to bind changeFontSize() as the click event handler and create a data object to pass the fruits ID to the function. Amend the code in the preceding step like this:
$('#trigger').show() .css('cursor', 'pointer') .click({id: 'fruits'}, changeFontSize);
    This time, the click() method takes two arguments. The first is an anonymous object that has one property: id with the value 'fruits'. The second argument is the name of the function that you want to be executed when the paragraph is clicked. Note that the function name is not followed by a pair of parentheses.
     
  1. Although the object used as the first argument to the click() method doesn't have a name, its properties are automatically transmitted to the function through the event object's data object. Don't worry if it sounds like voodoo magic. Getting the value involves a couple of simple edits to the changeFontSize() function. Change the first two lines of the function definition like this:
function changeFontSize(e) { var list = document.getElementById(e.data.id),
    Instead of passing id as the argument to the function, you pass e, which captures the event object. Any values passed to the function as a data object can be retrieved as properties of e.data. So, the id property of the anonymous object you created in step 9 can be accessed as e.data.id.
     
  1. Save the page and test it in a browser or Live view. It should work exactly the same as before. You can check your code, if necessary, against jq_09.html.
Mixing jQuery with JavaScript syntax
 
Apart from the way the argument is passed to the changeFontSize() function, the code inside the function is standard JavaScript—proof, if you needed it, that JavaScript and jQuery work in harmony with each other. However, you need to be careful when you mix both types of syntax.
 
As it stands, the changeFontSize() function obtains a reference to the fruits unordered list using the standard JavaScript getElementById() method. Because you're using jQuery, you could use a jQuery selector instead like this:
 
var list = $('#' + e.data.id)
Note: You need to prefix the ID with a hash sign because jQuery uses CSS selectors.
 
However, once you obtain a reference to the unordered list like this, you can't use it with the style object, because jQuery uses the css() method instead. The function would need to be rewritten like this:
 
function changeFontSize(e) { var list = $('#' + e.data.id), fontSize = list.css('font-size'), sizes = [16, 20, 24, 28], len = sizes.length, i; if (!fontSize) { list.css('font-size', sizes[1] + 'px'); } else { for (i = 0; i < len; i++) { if (i == len - 1) { list.css('font-size', sizes[0] + 'px'); } else if (fontSize == sizes[i] + 'px'){ list.css('font-size', sizes[i + 1] + 'px'); break; } } } }
There's a copy of the revised function in jq_10.html.
 
Note: For the sake of convenience, the exercises in this tutorial locate the jQuery document-ready handler in the same file as the HTML. Except for very short scripts, it's more common to store the jQuery code in an external file and link it to the page after the jQuery library.
 

 
Where to go from here

The jQuery slogan is "Write less, do more." It certainly lives up to its promise. Web designers should feel at home with the way jQuery selects HTML elements by passing a CSS selector to $(). Although the examples in this tutorial used simple selectors, jQuery accepts any CSS selector, greatly simplifying the process of selecting elements.
 
Using jQuery methods also simplifies changing the contents of web pages in response to events. Where jQuery can be more challenging is the way methods perform different, albeit related, functions depending on the number of arguments. For example, the css() method gets an existing value when you pass it the name of a property, but it sets a new value if you pass the value as the second argument. The method even accepts an object as its argument, allowing you to set multiple properties in a single operation.
 
Fortunately, jQuery is extremely well documented. The online documentation contains links to tutorials and a reference section organized according to subject. Each method has its own reference page complete with practical examples.
 
Several books are devoted to jQuery. The following two are particularly recommended:
 
Also be sure to check out the following resources on Adobe TV: