jQuery in Action
jQuery fundamentals
9
for most page authors to need the services provided by some of these functions; we
won't be looking at the majority of these functions in detail until chapter 6 as a
preparation for writing jQuery plug-ins. But you will see a few of these functions
put to use in the upcoming sections, so we're introducing their concept here.
won't be looking at the majority of these functions in detail until chapter 6 as a
preparation for writing jQuery plug-ins. But you will see a few of these functions
put to use in the upcoming sections, so we're introducing their concept here.
The notation for these functions may look odd at first. Let's take, for example,
the utility function for trimming strings. A call to it could be
$.trim(someString);
If the
$.
prefix looks weird to you, remember that
$
is an identifier like any other
in JavaScript. Writing a call to the same function using the
jQuery
identifier,
rather than the
$
alias, looks a bit more familiar:
jQuery.trim(someString);
Here it becomes clear that the
trim()
function is merely namespaced by
jQuery
or
its
$
alias.
NOTE
Even though these elements are called the utility functions in jQuery doc-
umentation, it's clear that they are actually methods of the
umentation, it's clear that they are actually methods of the
$()
function.
We'll put aside this technical distinction and use the term utility function to
describe these methods so as not to introduce conflicting terminology
with the online documentation.
describe these methods so as not to introduce conflicting terminology
with the online documentation.
We'll explore one of these utility functions that helps us to extend jQuery in sec-
tion 1.3.5, and one that helps jQuery peacefully coexist with other client-side
libraries in section 1.3.6. But first, let's look at another important duty that
jQuery's
tion 1.3.5, and one that helps jQuery peacefully coexist with other client-side
libraries in section 1.3.6. But first, let's look at another important duty that
jQuery's
$
function performs.
1.3.3 The document ready handler
When embracing Unobtrusive JavaScript, behavior is separated from structure,
so we'll be performing operations on the page elements outside of the document
markup that creates them. In order to achieve this, we need a way to wait until
the
so we'll be performing operations on the page elements outside of the document
markup that creates them. In order to achieve this, we need a way to wait until
the
DOM
elements of the page are fully loaded before those operations execute.
In the zebra-striping example, the entire table must load before striping can
be applied.
be applied.
Traditionally, the
onload
handler for the
window
instance is used for this pur-
pose, executing statements after the entire page is fully loaded. The syntax is typ-
ically something like
ically something like
window.onload = function() {
$("table tr:nth-child(even)").addClass("even");
};