Java Reference
In-Depth Information
Testing Your jQuery Installation
At the heart of jQuery is the $() function (called the jQuery function), which returns jQuery objects.
The jQuery function is quite powerful because it allows you to select elements by passing CSS selectors,
create elements by passing HTML, and wrap jQuery functionality around DOM objects by passing the
DOM objects you want to add functionality to.
To illustrate the jQuery function and the objects it returns, assume you want to run some code when the
page loads. In plain JavaScript, you know you can assign a function to handle the window's load event.
The jQuery equivalent is quite different:
function document_ready()
{
alert(“Hello, jQuery World!”);
}
// the normal way
onload = document_ready;
// the jquery way
$(document).ready(document_ready);
Look at the last line of this code, which calls the jQuery function and passes the document DOM object
to it. The jQuery function returns a jQuery object, of which ready() is a method. By passing a DOM
object to the jQuery function, you've actually created a new object that wraps itself around the DOM object.
This might be better understood with the following code:
var jDocument = $(document);
jDocument.ready(document_ready);
This code achieves the same results as the previous code, except you have a jQuery object contained in
the jDocument variable, which you can reuse.
It's important to note that jQuery objects cannot be used in place of DOM objects. In the previous
example, the jQuery function returns a completely different object than the document object it was
passed.
This type of reuse — assigning a variable and reusing it later — is perfectly fi ne to use with jQuery
objects, but jQuery adds the ability to chain method calls together. If the idea of method chaining is
new to you, then consider the following code:
$(document.body).attr(“bgColor”, “yellow”).html(“<h1>Hello, jQuery World</h1>”);
The jQuery object has many methods, and nearly all of them return the current jQuery object. Because
of this, you can call one method after another, thus enhancing readability while writing less code. This
code uses the jQuery function and passes the document.body DOM object to it. Immediately after the
function call, you call the attr() method to set the bgColor attribute to yellow. Since the jQuery func-
tion returns a jQuery object encapsulating a reference to the document.body DOM object, the bgColor
attribute is set on the document.body DOM object.
After the attr() method call is yet another method call because attr() returns the same jQuery
object encapsulating the document.body DOM object. The second method is the html() method,
Search WWH ::




Custom Search