Chapter 8. Events
Introduction
Events are the main method of communication between a user and a website or web application. Most of our JavaScript/jQuery coding will be run in response to a variety of user and browser events.
By user events, I mean basically keyboard and mouse interaction like
click
, mousedown
, keypress
, etc. Browser
events are mainly DOM events like document.ready
, window.onload
, and many other events
related to DOM elements.
When coding Ajax applications, we also have custom jQuery
Ajax events that are dispatched during the process of an Ajax
request, that is, ajaxSend
, ajaxComplete
, ajaxError
, and some more.
jQuery’s API is very consistent, especially when it comes to events. Attaching a handler to any kind of event is done using the same code structure:
jQuery(listener
).bind('eventName'
,handlerFunction
);
This syntax also applies to a fourth category that I haven’t mentioned yet. jQuery’s event system can be used for event-driven programming[1] in which you can create your own custom events that can be bound and triggered as regular ones.
jQuery also provides a shortcut method for most common browser and Ajax events. A model call using a shortcut would look like this:
jQuery(listener
).eventName
(handlerFunction
);
When using bind()
, eventName
will be a string wrapped in either
single or double quotes. When
using the shortcut, you simply put the event’s name as the jQuery
method’s name.
Here’s an example of binding a click handler, with and without the shortcut: ...
Get jQuery Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.