HTML and CSS Reference
In-Depth Information
The first line is important, because you'll see it or a variation of it in nearly every jQuery
$(document).ready(function() {
First, $ is the name of a function provided 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
To the right, you 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 convenience
methods for binding events to objects or elements, and in this case, will be used to bind
an anonymous function to the document's ready event. It's roughly equivalent to win-
dow.onload , the method call I used in the previous lesson to cause JavaScript to execute
when the page loads, but it works a bit differently. 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 your users.
jQuery's document.ready event, on the other hand, fires when the DOM for the page has
been fully constructed. 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 that a shortcut is provided to make doing so even
easier. The previous line 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(function(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 I
pass to jQuery, and it works exactly as it does with CSS. The click() method binds a
function to the onclick event for all the elements matched by the selector it's called on,
in this case, all the <a> tags on the page.
Search WWH ::

Custom Search