Working with Events in jQuery
- Binding an Event Handler to an Event
- Binding Multiple Event Handlers
- Binding Event Handlers Using Shortcuts
- Calling Event Handlers Only Once
- Unbinding Event Handlers
- Using the Event Object
- Getting Mouse Coordinates
- Getting the Event Type
- Capturing Keystrokes
- Capturing Hover Events
- Getting Event Targets
When you move the mouse, for example, an event object is created in both browsers that contains the mouse position information, such as the X and Y location of the mouse. But the way you access that event object is entirely different in the two browsers.
The nightmare only begins there. You access the mouse position and other items such as the page element that the mouse is over through event object properties. And those properties have different names—and sometimes different meanings—depending on the browser in which your code is running.
That's where jQuery comes in. jQuery unifies event handling with a single way of attaching event handlers to page elements, a single type of event object, and a single set of event object properties. This alone is worth the price of admission.
jQuery also allows you to attach multiple event handlers to page elements and uses standard names (such as click) for events, making working with these events easier. It also makes the event object easily available to event handlers by simply passing that object to event handlers.
That's not to say that event handling in jQuery is not sophisticated. You can also cancel event bindings and create event handlers that execute only once. You can even call alternate event handlers every other time an event happens.
It all takes place in jQuery. Let's start digging into event handling now.