Web Development with jQuery®

(Elliott) #1

(^32) ❘ CHAPTER 2 SELECTING AND FILTERING
As I touched on briefl y in Chapter 1, jQuery provides its own event called ready, which is fi red as
soon as the DOM has fi nished loading, which is different from the onload or load event in that
with the load event, you have to wait for all the images to load too before that event will fi re. Most
of the time, you don’t need to wait so long; you just want to start working with the document and
adding behavior as soon as the DOM has fi nished loading. That’s what the fi rst line of code does.
Now that the DOM is loaded, you want to add behaviors to the document using script. The fi rst
item is an example of jQuery’s Selectors API in action: it is a function call to the dollar sign method
that uses a selector that picks up all elements.
$('a')
When those
elements are selected, you more than likely want to do something with them. In
this example, you add a click event to each of the
elements that you selected. The click event is
added via a click method that is unique to jQuery:
$('a').click(
function(event)
{
What you see here is an example of how jQuery lets you chain methods together. First, you selected
a bunch of
elements; now, you’re applying a click event directly to each of those elements
via a new method called click() that’s chained to the end of your selection.
Within the click() method, you are passing a single anonymous (that is, nameless) function (these
are also called closures or lambda functions) that contains the instructions that you want to be
executed when each
element is clicked by a user.
function(event)
{
var node = $(this);
var target = node.attr('target');
var href = node.attr('href');
if (target === undefined && href !== undefined)
{
switch (true)
{
case href.indexOf('http://') !== -1:
case href.indexOf('https://') !== -1:
case href.indexOf('.pdf') !== -1:
{
node.attr('target', '_blank')
.addClass('exampleLinkAutoTarget');
break;
}
}
}
}
The anonymous function contains one argument, event, which represents the event object. The
event object is just like what you would use with the standard W3C Event API, and Internet
http://www.it-ebooks.info

Free download pdf