- A mouse click
- Mousing over a hot spot on the web page
- Submitting an HTML form
- A keystroke
- onload and unload – fired when a user enters/leaves the page
These days, unfortunately, due to a browser war late 1990s between Netscape and Microsoft, two different, incompatible, event models exist. Luckily, jQuery (and other libraries too) provides an event API and hides the different event implementations.
2. jQuery’s event API
At this moment, jQuery 1.7 has just been released and provides a brand new event API. The old functions bind, unbind, live, die, delegate and undelegate are now depregated and replaced by just two functions: on and off.
Below is a list showing the old and new event binding methods:
The main reason given for this rewrite was the need to improve the performance for event delegation.
Below are two sections digging a little bit deeper into jQuery’s event API.
3. Event delegation
When a page grows in size and complexity, incorrect binding of an event-callback to an event can have a major impact on the responsiveness of a web application. For example, binding a click handler to each item in a very huge list is a real performance killer! The solution however is simple, “Event Delegation”.
So instead of doing
you should bind the callback function to the parent of these items, like this
Now the event is delegated and just bound once
4. Namespaced events
jQuery provides a system for namespacing bound events for easier triggering and removal. Simply add a classname to your event when you declare it
To trigger the event the namespace should be mentioned explicitly, or no namespace at all. For example:
Also the removal of one event handler is easy now