ptg16476052
504 LESSON 18: Using jQuery
jQuery translates the selectors that developers use into the calls it needs to make on the
document object to retrieve the proper list of elements. Thus, you can use a selector like a
to find all the links on a page or a.archives to find all the links with the class archives,
and jQuery will access the DOM in whatever way works with the user’s browser and
return the list of elements they selected.
Binding Events
Most JavaScript development involves binding event handlers to events. Whether it’s
making sure that JavaScript code that initializes things loads at the right time, or adding
interactivity by associating code with actions the user takes on the page, you’re dealing
with event binding.
jQuery properly binds events so that multiple handlers can be bound to the same event,
across all browsers. If you bind your events using jQuery, you never have to worry about
overriding events bound in another script. Also, as you saw in the previous example,
jQuery makes it easy to bind handlers to multiple elements at once. For example, the fol-
lowing code would dis able all the links on the page:
$("a").click(function(event) { event.preventDefault(); }
jQuery enables you to refer to the object representing the event itself in your handler. To
do so, add the event parameter to the anonymous function representing the event handler.
You can name the parameter whatever you like, in this case. I named it event. I then call
the preventDefault method on the event. That method, provided by jQuery, indicates
that the default action associated with the event should not be performed. The default
action of a link is to change the browser’s location to the URL in the link, but this event
handler prevents that from happening.
Here’s a more useful example. Let’s say that I want links to external sites to open in a
new window, and all the links to external sites use a fully qualified URL whereas local
links do not. I could use the following event handler:
$(function () {
$("a").click(function (event) {
if (null != this.href && this.href.length > 4
&& this.href.substring(0, 4) == "http") {
event.preventDefault();
window.open(this.href);
}
});
});