3 May 2011
An understanding of CSS and basic JavaScript concepts.
Article: Introduction to JavaScript
jQuery: Download
Beginning
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:
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.
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 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?
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:
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.
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.
</body> tag, as shown in Figure 2.
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.
<script> element that you inserted in the previous exercise and the closing </body> tag.<script> tags in the space you just created.Inside the new <script> block, type $(function() {.
<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.
<script> tags.
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.
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.
Dreamweaver automatically adds a matching closing quotation mark and displays a list of code hints for HTML elements (see Figure 5).
<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.
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>');
});
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.
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.
body') on the preceding line. Then type a dot. Dreamweaver brings up the code hints for jQuery methods again.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.
$(function() {
$('body').append('<p>This paragraph was added dynamically.</p>')
.addClass('reverse');
});
<body>, changing the background color to black and the text color to white (see Figure 8).
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.
The examples in the Introduction to JavaScript 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.
<h2> headings, each followed by a single paragraph.<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.
hide() method to the selector like this:$(function() {
$('h2 + p').hide();
});
This hides the three paragraphs when the page loads (Figure 9).
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.
<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.
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) {
});
});
<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();
});
});
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.
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.
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');
});
$(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.
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.
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.
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.
</body> tag, and attach the jQuery library and insert a jQuery document ready event handler as in the previous exercises.<head> of the page, select the changeFontSize() function definition (without the surrounding <script> tags) and cut it to your clipboard.<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>
trigger like this:<p id="trigger">Change list font size.</p>
<style> block in the <head> of the page to set the display property of trigger to none:<style>
#trigger {
display:none;
}
</style>
changeFontSize() function definition:$('#trigger').show()
.css('cursor', 'pointer');
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.
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.
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.
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:
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.
Tutorials and samples |
| 04/23/2012 | Resolution/Compatibility/liquid layout |
|---|---|
| 04/20/2012 | using local/testing server with cs5 inserting images look fine in the split screen but do not show |
| 04/18/2012 | Ap Div help |
| 04/23/2012 | Updating |