CHAPTER 12 JQUERY
275
At the bottom of the page, add a script block containing a very simple jQuery function (you will see at a
better way of wiring up this script to the click of a button shortly):
<script language="javascript">
function hellojQuery() {
$("#div1").html("hello jQuery");
}
</script>
Press F5 to run your application and click the Hello jQuery button; the text of the first div should change
to “hello jQuery”.
How Does It All Work?
Probably the only weird looking bit of code is this line:
$("#div1").html("hello jQuery");
Let's dissect it:
• The $ sign is an alias that tells the browser to use the jQuery namespace. You could
instead replace it with jQuery("#div1") if you want, but that would involve more
typing, so don’t be silly.
• The text "#div1" tells jQuery to select all elements with an ID of div1. jQuery will
return a wrapped set of all elements matching the selector. Note that even if your
selector returns just one element, you will be working with a wrapped set. jQuery
also allows you to utilize CSS type selectors and adds a few of its own that you will
look at shortly.
• The .html() function is jQuery's version of the innerHTML property and it applies
the change to all elements in the returned set.
USING .HTML()
Warning: note the difference when using .html() and .innerHTML:
.html("hello jQuery")
.innerHTML="hello jQuery"
Selecting Elements
jQuery’s strength is the ease with which you can select and manipulate elements on the page. We have
used a selector method already to select all div elements that have an ID of div1:
$("#div1").html("hello jQuery");
CHAPTER 12 JQUERY
276
jQuery supports many different ways to select an element or elements that should meet all but the
most awkward requirements. Table 12-1 lists examples of other selection methods you might want to use.
Table 12-1. Example selection methods
Sel e ct o r
Sel e ct e d
$("#div1") Select a div with ID of div1.
$("div") Select all divs.
$("div.standardDiv") Select all divs with a class of standardDiv.
$(".standardDiv") Select all elements with a class of standardDiv.
$("#div4 #div5") Select a div with ID of div5 nested inside a div with id of div4.
$(".standardDiv")[0].innerHTML=
"hello jQuery";
Select the first element of a group of divs with class of
standardDiv and set innerHTML property to "hello jQuery".
Note that the use of traditional properties and jQuery selectors
is sometimes possible.
CSS Selectors
In addition to the previous standard selectors, more modern selectors are also available (browser
support may differ, but you are probably safe with IE 7+ and Firefox 3+):
Table 12-2. CSS Selectors
Sel e ct o r
Sel e ct e d
$("div:first") First div
$("div:last") Last div
$("div:even") Even-numbered divs
$("div:odd") Odd-numbered divs
$("div:first-child") First child element
$("div:last-child") Last child element
$("div:nth-child(3)") Third child element
$("a[href^=http://]") Any hyperlink starting with the text http://
CHAPTER 12 JQUERY
277
Sel e ct o r
Sel e ct e d
$("a[href$=.zip /]") Any hyperlink ending with .zip
$("a[href*=Microsoft") Any hyperlink with the text Microsoft in it
$("input[type=button]")[0].innerText="hello
jquery2"
Selects first input element of type button and
changes innerText property to "hello jquery2"
$(":checked") Gets all check boxes that are checked
$(":disabled") All disabled elements
$(":enabled") All enabled elements
jQuery Selectors
jQuery also has provides some inbuilt selectors of its own:
Table 12-3. jQuery selectors
Sel e ct o r
Effec t
$(":button")[0].innerText="hello jquery2"; Change innerText property of first button element
$(":contains(alex)") All elements containing text alex
$(":hidden") All hidden elements
$(":selected") All selected elements
$(":visible") All visible elements
$("div:not(.standardDiv)") Select all div elements that do not have a class of
standardDiv
Working with Sets
So you have used one of the preceding selector methods and now have a collection of matching
elements. How can you work with them? jQuery has a number of different methods to work with
collections.
CHAPTER 12 JQUERY
278
Table 12-4. Different ways to manipulate sets.
Exa mple
Me ani ng
$("div").get(0) Get first element in set
$("div")[0] Get first element in set
$("div").get() Gets all elements in set
$("div").size() Gets size of set
.each() method
The .each() method works similar to the foreach statement in C# or Visual Basic and allows you to
iterate through a set of elements. The following example iterates through a set of divs, modifying the
innerHTML property on each element.
function showDivNumber()
{
$("div").each(function(index) {
this.innerHTML = "I am div number " + index;
});
}
Of course if you just wanted to set the same text to each div element you could apply the change to the
wrapped set as follows:
$("div").html("I am a div");
Working with Attribute Values and CSS
jQuery provides methods to read, set and remove attributes on page elements.
Table 12-5. Examples of working with attributes
Exa mple
Me ani ng
alert($("#div1").attr("id")); Retrieving id attribute from div
$("#div1").attr("title", "hello"); Sets the title attribute to “hello”
$("#div1").removeAttr("title") Removes title attribute
$("#div1").addClass("specialDiv"); Adds specialDiv CSS class to element
CHAPTER 12 JQUERY
279
Writing Elements Dynamically
jQuery allows you to easily insert elements on a page. The following code appends a p tag to the div with
id of div1:
<script>$("<p>hello I am dynamically added text</p>").appendTo("#div1")</script>
You can also insert an element after the target element with the .insertAfter() method:
<script>$("<p>hello I am dynamic text</p>").insertAfter("body")</script>
Remember that adding elements dynamically works slightly differently in IE than Firefox. While
researching this chapter, I was playing around with the following script:
<script>$("<p>hello I am dynamic text</p>").appendTo("body")</script>
This works fine in Firefox but will give you a strange error when run in IE 7 (see Figure 12-3). Can
you guess why?
Figure 12-3. Internet explorer error
Why does this work fine in Firefox and not IE? Well it is quite simple really; the problem is that the
document was not fully rendered yet, so the script couldn’t find the element when it ran. This is a
common problem with JavaScript. So how can we specify that a script should run only when the
document is fully loaded?
Running a Script on Page Load
One solution to the previous problem is to run the script inside the window.onload() function, but the
script will not be run until the entire page including images is loaded.
jQuery offers a neat solution with the ready event:
$(document).ready(function() {
$("<p>hello I am dynamic text</p>").appendTo("body");
});
This is a good way to ensure that the page is loaded before the script and will resolve the earlier
issue. You must ensure that you have added any elements to the page before running code that
manipulates them.
CHAPTER 12 JQUERY
280
Adding Functions
A common problem many designers and developers encounter is the separation of design from code.
Many developers (in fact, I got you to do this in the very first example) if asked to call a JavaScript
function when a button is clicked will write something such as this:
<input id="cmdTest" type="button" value="Hello jQuery"
onclick="javascript:hellojQuery();" />
However this is not the best way because it is very vulnerable to polo neck, snowboarding designer
corruption and isn’t standards compliant.
jQuery offers a neat solution with the .bind() method. The following code binds the hellojQuery()
function to the click of the cmdTest button:
$("#cmdTest").bind('click', hellojQuery());''
Animation/Effects
Many people become aware of jQuery through seeing one of its many impressive graphical effects.
Let’s check out the fadeOut effect using our original example.
1. Go back to default.htm and change the helloJQuery() function to contain the following:
$("#div1").fadeOut();
2. Press F5 to run your application,
3. Click the Hello jQuery button,
4. The div should then fade out of view.
Effect Overloads
Most of the effects in jQuery are overloaded, allowing fine-grained control (see Table 12-6).
Table 12-6. Different overloads of fadeOut method
Exa mple
Me ani ng
$("#div1").fadeOut(); Basic effect with default options
$("#div1").fadeOut(10000); Effect time specified in milliseconds
$("#div1").fadeOut('slow'); Specifies the time the effect will take to run: slow,
normal, or fast