Skip to Main Content
jQuery Cookbook
book

jQuery Cookbook

by Cody Lindley
November 2009
Intermediate to advanced content levelIntermediate to advanced
480 pages
11h 50m
English
O'Reilly Media, Inc.
Content preview from jQuery Cookbook

Chapter 8. Events

Ariel Flesler

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: ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

jQuery UI in Action

jQuery UI in Action

TJ VanToll
Head First jQuery

Head First jQuery

Ryan Benedetti, Ronan Cranley

Publisher Resources

ISBN: 9780596806941Supplemental ContentErrata Page