HTML and CSS Reference
In-Depth Information
Binding Events
In the introductory script, I provided one example of event binding. The biggest advan-
tage of binding events using jQuery (or other popular JavaScript libraries) is that they are
nondestructive. There's a big problem with writing code like this:
window.onload = function () { // Do stuff. }
If some other script also binds an event to the window.onload event, one of the two will
win, and the other event binding will be ignored. This can be a big problem on web
pages that include multiple external JavaScript files. jQuery (and other libraries) bind the
events in such a way that multiple handlers can be bound to a single event without
unbinding the other handlers. The functionality may still conflict, but the event binding
itself will work.
16
Another advantage of jQuery is that you can bind handlers to multiple elements at once.
For example, the following code would disable all the links on the page:
$(“a”).click(function(event) { event.preventDefault(); }
In this case, I added the event parameter to my event handler so that I can refer to that
event within the handler. I then call the event.preventDefault() method, which is part
jQuery, to tell the browser not to do whatever the default action of the event was. In this
case, the browser won't follow the link because that action was prevented.
Here's a more useful example. Let's say that I want links to other 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);
}
});
});
In this case, I examine the href attribute of the link the user clicked. If it starts with
“http,” I prevent the default action and open a new window with the link. If it doesn't,
the default action is allowed to continue. Instead of adding special classes to external
links on the page or using the onclick attribute for each of them to open new windows, I
just used jQuery's selector functionality and a bit of programming to take care of it for me.
jQuery provides methods for binding most events to jQuery objects. For a more full list
of events jQuery supports, see http://api.jquery.com/category/events/.
 
 
Search WWH ::




Custom Search