Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

502 LESSON 18: Using jQuery


The first <script> tag loads the external jQuery script. The second contains the script I
wrote. This script causes an alert to be displayed whenever a user clicks a link. I’ll break
it down line by line.
The first line is important because you’ll see it or a variation of it in nearly every jQuery
script:
$(document).ready(function() {
First, $ is the name of a function declared by jQuery, and document is an argument to
that function. The $ function selects the set of elements matched by the selector provided
as an argument. In this case, I’ve passed document as the argument, and it matches the
document object—the root object of the page’s document object model. Usually, the
selector is a CSS selector, but the document object is an alternative that you can use, as
well.
To the right, you’ll see a call to the ready method, which is applied to the elements that
the selector matches. In this case, it’s the document object. jQuery provides convenient
methods for binding events to objects or elements, and in this case, it will be used to bind
an anonymous function to the document’s ready event. The “ready” event is provided by
jQuery.
The window object supports the onload event, which is what’s normally used to execute
JavaScript when the page is displayed. The window.onload event doesn’t “fire” (call any
methods that are bound to it) until the page has fully loaded. This can be a problem for
pages that contain large images, for example. The JavaScript code won’t run until the
images load, and that could lead to strange behavior for users.
jQuery’s document.ready event, however, fires when the page has been fully con-
structed. This can cause the JavaScript to run a bit earlier in the process, while images are
being downloaded. With jQuery it’s customary to perform all the work you want to occur
when the page loads within an anonymous function bound to the document.ready event.
It’s so common, in fact, that a shortcut is provided to make doing so even easier. The line
above can be rewritten as follows:
$(function() {
jQuery knows that you intend to bind the function to the document.ready event. Here’s
the code that’s bound to the event:
$("a").click(f unction(event) {
alert("You clicked on a link to " + this.href );
});

This code binds a function that prints an alert message containing the URL of the link
that the user clicked on to every link on the page. In this case, I use "a" as the selector
Free download pdf