jQuery Event Handlers

The event handler functions in the examples above expect no arguments and return no values. It is quite normal to write event handlers like that, but jQuery does invoke every event handler with one or more arguments, and it does pay attention to the return value of your handlers. The most important thing you should know is that every event handler is passed a jQuery event object as its first argument. The fields of this object provide details (like mouse pointer coordinates) about the event. jQuery simulates the W3C standard Event object, even in browsers that do not support it (like IE8 and before), and jQuery event objects have the same set of fields in all browsers. This is explained in detail in The jQuery Event Object.

Normally, event handlers are invoked with only the single event object argument. But if you explicitly trigger an event with trigger() (see Triggering Events), you can pass an array of extra arguments. If you do this, those arguments will be passed to the event handler after the first event object argument.

Regardless of how they are registered, the return value of a jQuery event handler function is always significant. If a handler returns false, both the default action associated with the event and any future propagation of the event are canceled. That is, returning false is the same as calling the preventDefault() and stopPropagation() methods of the Event object. Also, when an event handler returns a value (other than undefined), jQuery stores that value in the result property of the Event object where it can be accessed by subsequently invoked event handlers.

Get jQuery Pocket Reference 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.