Events
jQuery offers a powerful and comprehensive event API. jQuery’s event API provides wrap-
per methods that accommodate most events in JavaScript. jQuery’s event API also provides
the capability to attach events it doesn’t explicitly support via its event methods. The jQuery
event API even has the capability to apply events to elements that might not even exist in the
document yet. Events can be neatly organized and namespaced within jQuery, another fea-
ture it offers above and beyond the baseline provided by JavaScript. Your events can be neatly
organized into named categories, which make it a lot easier to manage events. Having named
events also makes it possible to easily remove them.
In this chapter, you learn everything you need to know to work with jQuery’s event API. You
learn how to use jQuery’s event wrapper methods such as click() or hover(). You also learn
how to use methods such as on() and off(). You can use the on() and off() methods to attach
an event handler function to any event, whether it is a native JavaScript event or a custom
event that you’ve created. The on() and off() methods can also attach events to elements that
might not even exist in the document yet. In addition, on() and off() can name and organize
events, which is useful if you need to manage or remove events as easily as creating them. You
also learn how to create completely custom events for your applications by virtue of the trig-
ger() method as well as the on() and off() methods. Custom events can make your own appli-
cations highly extensible and fl exible.
The Various Event Wrapper Methods
jQuery’s event API started with the goal of providing a bridge between the different browsers’
disparate methods for dealing with event attachment. There was a time in the not-so-distant
past that there was the Microsoft way of dealing with events, and then there was the standard-
ized way of dealing with events. Because of Microsoft’s work on Internet Explorer, this is no
longer an issue, and you have to worry about this only if you need to support those older ver-
sions of Internet Explorer that don’t support the standard way of attaching events. Thankfully,
jQuery already deals with the browser differences for you. The jQuery 1.x branch provides
legacy support for versions of Internet Explorer that don’t support the standardized way.