SCRIPTING THE WEB – PART 2 -

INTRODUCTION TO JQUERY

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 exercise introduces you to the basics of jQuery.

Note: You can complete this exercise with any version of Dreamweaver or a text editor, but you won't have the benefit of code hints unless you are using Dreamweaver CS5.5. Just copy the finished code instead.

What is jQuery?

According to the jQuery website ( "jQueryis designed to change the waythat 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 JavaScriptlibrary, 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 DocumentObject 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 DojoToolkit ( MooTools ( the Yahoo! UI Library ( and the AdobeSpryframework ( 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 exercise, it is recommend that you work with a local version of the jQuery library. The example files contain a copy of jQuery 1.7.2, which is the current version (April, 2012).

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.

  1. Create a new folder in your MySites folder called Scripting the Web - Part 2.
  1. Locate the folder on the K:\ drive under K:\Sue Brandreth called Scripting the Web - Part2 files and copy its contents into your Scripting the Web - Part 2 folder.
  1. Define a new Dreamweaver site called Scripting the Web - Part 2 and set the root folder as the Scripting the Web - Part 2folder that you have just created.

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 the web page jq_01.html and view in Code or Split View.
  1. Position the insertion point immediately before the closing </body> tag, and click Script in the Commoncategory of the Insert panel, or select Insert > HTML > Script Objects > Script.
  1. 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.7.2.min.js. Click OK. The filename should now be listed in the Script dialog box, as shown below:

  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 below:

<p>This paragraph is part of the original HTML markup.</p>

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

</body>

</html>

  1. Save the web page jq_01.html.

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.

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 exercise, we are going to use only the shorthand version. It's the simplest and most commonly used.

  1. Continue working with the same file as before (jq_01.html). Alternatively, use jq_02.html.
  1. Insert several new lines between the <script> element that you inserted in the previous exercise and the closing </body> tag.
  1. Add a pair of opening and closing <script> tags in the space you just created.
  1. Inside the new <script> block, type $(function() {
  1. 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.
  1. Right-click and select Create New Snippet from the context menu.
  1. Type jQuery Document Ready Handler in the Name field of the Snippet dialog box.
  1. Dreamweaver copies the selected code into the "Insert before" pane. Click inside the blank line, select the remaining code, and cut it to your clipboard. Paste the code into the "Insert after" pane.

The Snippet panel should appear as shown below.

  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.
  1. 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:
  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:

  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.

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.

  1. 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 as shown below:

The HTML passed as an argument to append() is added to the page.

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>

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.
  1. Place 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.
  1. 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.
  1. Select addClass from the code hints. This inserts the method name followed by an opening parenthesis.
  1. 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. If there were more classes, the hints would list all of them alphabetically.
  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 web 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 colour to white:

Both jQuery methods have been applied to the <body> of the page.

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

Traditional JavaScript uses 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 behavioural 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 the web pagejq_05.html. The page contains three <h2> headings, each followed by a single paragraph.
  1. In Code View, attach the jQuery library and create a jQuery document-ready event handler in the same way as in the first exercise.
  1. 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

  1. Save the web page and view the page in a browser:

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 shown below, there are three options:
  1. 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 anonymousfunction. It's this third option that you want. Select it and press Enter/Return.

The code now looks like this: