O'Reilly logo

JavaScript: The Definitive Guide, 6th Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Handling Events with jQuery

As we saw in Chapter 17, one of the difficulties of working with events is that IE (until IE9) implements a different event API than all other browsers do. To address this difficulty, jQuery defines a uniform event API that works in all browsers. In its simple form, the jQuery API is easier to use than the standard or IE event APIs. And in its more complex full-featured form, the jQuery API is more powerful than the standard API. The subsections below have all the details.

Simple Event Handler Registration

jQuery defines simple event-registration methods for each of the commonly used and universally implemented browser events. To register an event handler for click events, for example, just call the click() method:

// Clicking on any <p> gives it a gray background
$("p").click(function() { $(this).css("background-color", "gray"); });

Calling a jQuery event-registration method registers your handler on all of the selected elements. This is typically much easier than one-at-a-time event handler registration with addEventListener() or attachEvent().

These are the simple event handler registration methods jQuery defines:

blur()          focusin()       mousedown()     mouseup()
change()        focusout()      mouseenter()    resize()
click()         keydown()       mouseleave()    scroll()
dblclick()      keypress()      mousemove()     select()
error()         keyup()         mouseout()      submit()
focus()         load()          mouseover()     unload()

Most of these registration methods are for common event types you are already familiar with from Chapter 17

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required