Last updated .
The handling of events is associated with much inconsistency between various browsers and DOM event models. jQuery shields the developer from all this by providing a unified model for attaching and writing event handlers.
Remember that, in the browser, events bubble up. This means that not only does an element get a chance to react on an event triggered on itself, but so do its ancestors, all the way up the document tree to the root. For example, in this document fragment, a handler for the click of the button can be attached to the button itself or either of its ancestors:
<div>
<fieldset>
<button></button>
</fieldset>
</div>
Another thing to note is that certain events have default, built-in behavior associated with them. For example, clicking an anchor element actually causes the browser to take action (navigating to the target URI), without there being any event handler associated with the element. This is usually termed the default action. That does not prevent one from attaching event handlers to, say, an anchor element.
The list of event types (names) is ever evolving and this is a long story by itself, full of inconsistencies and browser failure - refer to this list of events.
An event handler is a function with the signature function(/*object*/ event)
and returning a boolean. The function context (the this
variable) will be a reference to the element to which the handler is attached.
Returning false from an event handler causes jQuery to stop the event bubbling and the default action for that particular event. This is equivalent to calling event.stopPropagation()
and
event.preventDefault()
. Returning true (or nothing) has no effect.
jQuery consolidates the event object into its own event object. The original event object can be accessed with event.originalEvent
. The members of the event object are:
The on method is the general method for attaching event handlers to elements. The method has the signature jQuerySet.on(/*object or string*/ eventNameOrObject[, /*string*/ selector][, /*any*/ data][, /*function*/ handler])
and it returns the jQuery set it is called on. The parameter of the on method are described here:
click.myNamespace.subNamespace
and this functionality may be used to group handlers.The following, very simple, example demonstrates event bubbling, in that a parent element gets to handle an event that was really triggered on a child element:
<div id="d0" style="width:400px;background-color:yellow;">
<button id="button1">Click me!</button>
</div>
<script>
jQuery("#d0").on("click", function (event) {
console.log("this.id: " + this.id + ", target.id: " + event.target.id);
});
</script>
// When the button is clicked, the handler logs: this.id: d0, target.id: button1
// When the div is clicked, the handler logs: this.id: d0, target.id: d0
Event delegation is the term used for the pattern, where an ancestor handles some events on behalf of some descendants. This has the advantage that the number of event handlers can be kept down; e.g. instead of attaching the same event handler to 100 rows of a table, the handler can simple be attached to the table itself. This has an added advantage becaus the set of children may be dynamic, and so defining the event handler on the ancestor frees you from detaching and attaching handlers to child elements dynamically as these are created.
The following example illustrates event delegation; one handler on a table handles the click event on behalf of descendants. Often, one will not be interested in handling the click on any type of descendant in the same handler. The below example uses the selector argument to specify that only click on button elements should trigger the event handler:
<table id="table0">
<tr><td>Some text</td><td><button>Some button</button></td></tr>
<tr><td>Some other text</td><td><button>Some other button</button></td></tr>
</table>
<script>
// handle click on descendant button:
jQuery("#table0").on("click", "button", null, function (event) {
console.log(event.target.nodeName);
});
</script>
An event handler can be shared by multiple elements:
<div id="d0" style="width:400px;background-color:yellow;">
<button id="button1">Click me!</button>
<button id="button2">Click me also!</button>
</div>
<script>
// One handler for both buttons:
jQuery("button").on("click", function (event) {
console.log(jQuery(this).text());
});
</script>
And likewise, an event handler can be set up to handle different types of events:
<button id="button1">Click me!</button>
<script>
// One handler for two event types:
jQuery("#button1").on("mousedown mouseup", function (event) {
console.log(event.type);
});
</script>
Multiple handlers can be defined for the same event on the same element. In the following example both handlers for the click event on a button are invoked when the button is clicked:
<button id="btnA">Button A</button>
<script>
jQuery("#btnA").on("click", function (event)
{
console.log("First handler");
});
jQuery("#btnA").on("click", function (event)
{
console.log("Second handler");
});
</script>
The next example shows how to specify event handlers using an object for the first argument to the on method:
<button id="button0">Click me!</button>
<script>
jQuery("#button0").on(
{
"mousedown": function (event)
{
console.log("mousedown");
},
"mouseup": function (event)
{
console.log("mouseup");
},
});
</script>
This simple example dumps all functions and properties of the event object, attached to a button:
<button id="myButton">Click me!</button>
<script>
jQuery("#myButton").on("click", function (event)
{
for (var m in event)
console.log('Name: ' + m + ', Type: ' + typeof event[m] + ', Value: ' + event[m]);
});
/*
This is the output to the console when the button is clicked:
Name: originalEvent, Type: object, Value: [object MouseEvent]
Name: type, Type: string, Value: click
Name: isDefaultPrevented, Type: function, Value: function (omitted)
Name: timeStamp, Type: number, Value: 30875875
Name: jQuery2140556194041130788, Type: boolean, Value: true
Name: toElement, Type: undefined, Value: undefined
Name: screenY, Type: number, Value: 86
Name: screenX, Type: number, Value: 48
Name: pageY, Type: number, Value: 17
Name: pageX, Type: number, Value: 48
Name: offsetY, Type: number, Value: 6
Name: offsetX, Type: number, Value: 37
Name: clientY, Type: number, Value: 17
Name: clientX, Type: number, Value: 48
Name: buttons, Type: number, Value: 0
Name: button, Type: number, Value: 0
Name: which, Type: number, Value: 1
Name: view, Type: object, Value: [object Window]
Name: target, Type: object, Value: [object HTMLButtonElement]
Name: shiftKey, Type: boolean, Value: false
Name: relatedTarget, Type: object, Value: null
Name: metaKey, Type: boolean, Value: false
Name: eventPhase, Type: number, Value: 2
Name: currentTarget, Type: object, Value: [object HTMLButtonElement]
Name: ctrlKey, Type: boolean, Value: false
Name: cancelable, Type: boolean, Value: true
Name: bubbles, Type: boolean, Value: true
Name: altKey, Type: boolean, Value: false
Name: delegateTarget, Type: object, Value: [object HTMLButtonElement]
Name: handleObj, Type: object, Value: [object Object]
Name: data, Type: undefined, Value: undefined
Name: isPropagationStopped, Type: function, Value: function (omitted)
Name: isImmediatePropagationStopped, Type: function, Value: function (omitted)
Name: preventDefault, Type: function, Value: function (omitted)
Name: stopPropagation, Type: function, Value: function (omitted)
Name: stopImmediatePropagation, Type: function, Value: function (omitted)
*/
</script>
The one method attaches event handlers just as the on method, but makes sure these handlers are removed again once they have been called once. The method has the same signature as the on method:
jQuerySet.on(/*object or string*/ eventNameOrObject[, /*string*/ selector][, /*any*/ data][, /*function*/ handler])
. Please refer to the on method for a description of the parameters.
With a method named on, there is bound to be another method named off doing the opposite. The off method detaches event handlers from elements. The method has the signature
jQuerySet.off(/*object or string*/ eventNameOrObject[, /*string*/ selector][, /*function*/ handler])
and it returns the jQuery set it is called on. The parameter of the off method are described here:
click.myNamespace.subNamespace
and this functionality may be used to group handlers.
Depending on which parameters you use when calling this method, you can remove event handlers at various levels of granularity. If you pass just the event name(s), all handlers related to these event types will be removed (for the elements in the set). If you have more than one handler per event type, you might wish to specify these to remove some and keep others around. If so, you cannot create the handlers when calling on as anonymous methods, because in that case there will be no way to reference them. Instead, the handlers must be defined as named functions or be kept around in variables, so that they can be referenced later.
A useful feature in relation to the removal of event handlers is the namespace feature: it allows one to group handlers by name, and thus remove all handlers with a specific namespace in one call.
The following example uses the namespace feature to group handlers. One button uses the namespace A and another the namespace B. A third button lets the user detach event handlers pertaining to a specific namespace (specified in the input field):
<button id="btnA">Button A</button>
<button id="btnB">Button B</button>
<button id="btnDetach">Detach click handler for namespace</button>
<label for="namespace">Namespace: </label>
<input id="namespace"></input>
<script>
// Button A click handler
jQuery("#btnA").on("click.A", function (event)
{
console.log(event.target.id);
});
// Button B click handler
jQuery("#btnB").on("click.B", function (event)
{
console.log(event.target.id);
});
jQuery("#btnDetach").on("click", function (event)
{
// Remove handlers for the namespace specified in the input field:
var namespace = "." + jQuery("#namespace").val();
jQuery("button").off(namespace);
});
</script>
It sometimes comes in handy to trigger events from code to simulate, say, the click of a button. Of course, one could simply wrap the event handler code in a named function and call that. But by using the trigger method, you get the benefits of
the whole event machinery, including the bubbling of events and default actions. The trigger method does the trick. It has the signature
jQuerySet.trigger(/*object or string*/ eventType[, /*any*/ data])
and it returns the jQuery set it is called on. When you call the method, event handlers of the appropiate type get called for all the elements in the jQuery set. In calling the method, you can pass the name of the event type for the first parameter. This causes jQuery to construct an event object on your behalf to be passed to the event handlers. Because the
event will be simulated, some properties are going to be missing from the event object. For example, all the properties related to keyboard state and cursor position are missing. Rather than relying on jQuery to construct the event, you can
construct one yourself and pass it as the first parameter when calling the trigger method. Just make sure to add a property called "type", with the name of the event type you wish to trigger. Plus any other properties you might need. jQuery will then still construct an event object,
but copy any properties you define in the passed-in object to the event object that handlers will receive - see example below.
Seing that the trigger method takes a data parameter, one might think that what you pass in this parameter ends up in the event.data property when a handler is called. This is not the case; the two are unrelated. Instead, you can add a parameter to the event handler function in addition to the event parameter. The data passed in the call of trigger then gets passed in that parameter.
The next example makes use of the data parameter in calling the trigger method:
<button id="btnA">Button A</button>
<script>
jQuery("#btnA").on("click", null, "Hi", function (event, extraData)
{
console.log(event.data);
console.log(extraData);
});
jQuery("#btnA").trigger("click", "Hello, click handler!");
// Logged in console:
// Hi
// Hello, click handler!
</script>
The following example illustrates what the event object looks like when calling the trigger method, including how to add custom data to that object. The properties and methods of the event object are logged to the console. Contrast this with the "regular" event object passed when the event is real, rather than simulated through calling the trigger method.
<button id="btnA">Button A</button>
<script>
jQuery("#btnA").on("click", function (event) {
console.log(event.myProperty);
// Dump event object members to console:
for (var m in event)
console.log('Name: ' + m + ', Type: ' + typeof event[m] + ', Value: ' + event[m]);
});
var event = {
type: "click",
myProperty: "Hi from myProperty",
};
jQuery("#btnA").trigger(event);
/*
LOGGED TO THE CONSOLE:
Hi from myProperty
Name: type, Type: string, Value: click
Name: myProperty, Type: string, Value: Hi from myProperty
Name: timeStamp, Type: number, Value: 1450197500682
Name: jQuery214016710440797372983, Type: boolean, Value: true
Name: isTrigger, Type: number, Value: 3
Name: namespace, Type: string, Value:
Name: namespace_re, Type: object, Value: null
Name: result, Type: undefined, Value: undefined
Name: target, Type: object, Value: [object HTMLButtonElement]
Name: delegateTarget, Type: object, Value: [object HTMLButtonElement]
Name: currentTarget, Type: object, Value: [object HTMLButtonElement]
Name: handleObj, Type: object, Value: [object Object]
Name: data, Type: undefined, Value: undefined
Name: isDefaultPrevented, Type: function, Value: function
Name: isPropagationStopped, Type: function, Value: function
Name: isImmediatePropagationStopped, Type: function, Value: function
Name: preventDefault, Type: function, Value: function
Name: stopPropagation, Type: function, Value: function
Name: stopImmediatePropagation, Type: function, Value: function
*/
</script>
You are not limited to dealing with the built-in events - the jQuery library allows one to use custom events, just like in any normal programming language. The next example sets up an event handler on document to handle a custom event type called myEventType that expects to receive some data as event arguments. These are tucked away in the event.myEventArgs property of the event object that jQuery passes to the handler. In this example, the event is triggered by clicking on a button, but in real life it could be in response to whatever happens in the application.
<button id="btnA">Button A</button>
<script>
// Set up event handler for custom event
jQuery(document).on("myEventType", function (event)
{
console.log(event.myEventArgs);
}
);
// Set up event handler for button click
jQuery("#btnA").on("click", function (event)
{
var event = {
type: "myEventType",
myEventArgs: "Some data",
};
// Fire custom event
jQuery(this).trigger(event);
}
);
</script>
This method works in the same way as the trigger method, with the crucial difference that no event bubbling takes place and no default actions are performed. Another difference between the two methods
is that triggerHandler returns the return value from the call of the event handler. The method signature is: jQuerySet.triggerHandler(/*object or string*/ eventType[, /*any*/ data])
. Please refer to the trigger method
for a description of parameters.
The blur method establishes an event handler for the blur event, or triggers the same event. The method signature is jQuerySet.blur([/*any*/ data] [,/*function*/ handler])
and it returns the jQuery set that
it is called on. Calling the method with no parameters is equivalent to calling the trigger method to trigger the blur event. Calling the method with one or two parameters is the same as calling the
on method to establish an event handler for the elements in the set. The data argument gets relayed to the event handler via the event.data property, and the handler argument is a reference
to the event handler function.
The next example demonstrates setting up an event handler for the blur event:
<button>Button A</button>
<button>Button B</button>
<script>
jQuery("button").blur("some data", function (event) {
console.log(event.data);
});
</script>
The change method establishes an event handler for the change event, or triggers the same event. The method signature is jQuerySet.change([/*any*/ data] [,/*function*/ handler])
and it returns the jQuery set that
it is called on. Calling the method with no parameters is equivalent to calling the trigger method to trigger the change event. Calling the method with one or two parameters is the same as calling the
on method to establish an event handler for the elements in the set. The data argument gets relayed to the event handler via the event.data property, and the handler argument is a reference
to the event handler function.
For an example, please refer to the example for the similar blur method.
The click method establishes an event handler for the click event, or triggers the same event. The method signature is jQuerySet.click([/*any*/ data] [,/*function*/ handler])
and it returns the jQuery set that
it is called on. Calling the method with no parameters is equivalent to calling the trigger method to trigger the click event. Calling the method with one or two parameters is the same as calling the
on method to establish an event handler for the elements in the set. The data argument gets relayed to the event handler via the event.data property, and the handler argument is a reference
to the event handler function.
For an example, please refer to the example for the similar blur method.
The dblclick method establishes an event handler for the dblclick event, or triggers the same event. The method signature is jQuerySet.dblclick([/*any*/ data] [,/*function*/ handler])
and it returns the jQuery set that
it is called on. Calling the method with no parameters is equivalent to calling the trigger method to trigger the dblclick event. Calling the method with one or two parameters is the same as calling the
on method to establish an event handler for the elements in the set. The data argument gets relayed to the event handler via the event.data property, and the handler argument is a reference
to the event handler function.
For an example, please refer to the example for the similar blur method.
The focus method establishes an event handler for the focus event, or triggers the same event. The method signature is jQuerySet.focus([/*any*/ data] [,/*function*/ handler])
and it returns the jQuery set that
it is called on. Calling the method with no parameters is equivalent to calling the trigger method to trigger the focus event. Calling the method with one or two parameters is the same as calling the
on method to establish an event handler for the elements in the set. The data argument gets relayed to the event handler via the event.data property, and the handler argument is a reference
to the event handler function.
For an example, please refer to the example for the similar blur method.
The focusin method establishes an event handler for the focusin event, or triggers the same event. The method signature is jQuerySet.focusin([/*any*/ data] [,/*function*/ handler])
and it returns the jQuery set that
it is called on. Calling the method with no parameters is equivalent to calling the trigger method to trigger the focusin event. Calling the method with one or two parameters is the same as calling the
on method to establish an event handler for the elements in the set. The data argument gets relayed to the event handler via the event.data property, and the handler argument is a reference
to the event handler function.
For an example, please refer to the example for the similar blur method.
The focusout method establishes an event handler for the focusout event, or triggers the same event. The method signature is jQuerySet.focusout([/*any*/ data] [,/*function*/ handler])
and it returns the jQuery set that
it is called on. Calling the method with no parameters is equivalent to calling the trigger method to trigger the focusout event. Calling the method with one or two parameters is the same as calling the
on method to establish an event handler for the elements in the set. The data argument gets relayed to the event handler via the event.data property, and the handler argument is a reference
to the event handler function.
For an example, please refer to the example for the similar blur method.
The keydown method establishes an event handler for the keydown event, or triggers the same event. The method signature is jQuerySet.keydown([/*any*/ data] [,/*function*/ handler])
and it returns the jQuery set that
it is called on. Calling the method with no parameters is equivalent to calling the trigger method to trigger the keydown event. Calling the method with one or two parameters is the same as calling the
on method to establish an event handler for the elements in the set. The data argument gets relayed to the event handler via the event.data property, and the handler argument is a reference
to the event handler function.
For an example, please refer to the example for the similar blur method.
The keypress method establishes an event handler for the keypress event, or triggers the same event. The method signature is jQuerySet.keypress([/*any*/ data] [,/*function*/ handler])
and it returns the jQuery set that
it is called on. Calling the method with no parameters is equivalent to calling the trigger method to trigger the keypress event. Calling the method with one or two parameters is the same as calling the
on method to establish an event handler for the elements in the set. The data argument gets relayed to the event handler via the event.data property, and the handler argument is a reference
to the event handler function.
For an example, please refer to the example for the similar blur method.
The mousedown method establishes an event handler for the mousedown event, or triggers the same event. The method signature is jQuerySet.mousedown([/*any*/ data] [,/*function*/ handler])
and it returns the jQuery set that
it is called on. Calling the method with no parameters is equivalent to calling the trigger method to trigger the mousedown event. Calling the method with one or two parameters is the same as calling the
on method to establish an event handler for the elements in the set. The data argument gets relayed to the event handler via the event.data property, and the handler argument is a reference
to the event handler function.
For an example, please refer to the example for the similar blur method.
The mouseenter method establishes an event handler for the mouseenter event, or triggers the same event. The method signature is jQuerySet.mouseenter([/*any*/ data] [,/*function*/ handler])
and it returns the jQuery set that
it is called on. Calling the method with no parameters is equivalent to calling the trigger method to trigger the mouseenter event. Calling the method with one or two parameters is the same as calling the
on method to establish an event handler for the elements in the set. The data argument gets relayed to the event handler via the event.data property, and the handler argument is a reference
to the event handler function.
For an example, please refer to the example for the similar blur method.
The mouseleave method establishes an event handler for the mouseleave event, or triggers the same event. The method signature is jQuerySet.mouseleave([/*any*/ data] [,/*function*/ handler])
and it returns the jQuery set that
it is called on. Calling the method with no parameters is equivalent to calling the trigger method to trigger the mouseleave event. Calling the method with one or two parameters is the same as calling the
on method to establish an event handler for the elements in the set. The data argument gets relayed to the event handler via the event.data property, and the handler argument is a reference
to the event handler function.
For an example, please refer to the example for the similar blur method.
The mousemove method establishes an event handler for the mousemove event, or triggers the same event. The method signature is jQuerySet.mousemove([/*any*/ data] [,/*function*/ handler])
and it returns the jQuery set that
it is called on. Calling the method with no parameters is equivalent to calling the trigger method to trigger the mousemove event. Calling the method with one or two parameters is the same as calling the
on method to establish an event handler for the elements in the set. The data argument gets relayed to the event handler via the event.data property, and the handler argument is a reference
to the event handler function.
For an example, please refer to the example for the similar blur method.
The mouseout method establishes an event handler for the mouseout event, or triggers the same event. The method signature is jQuerySet.mouseout([/*any*/ data] [,/*function*/ handler])
and it returns the jQuery set that
it is called on. Calling the method with no parameters is equivalent to calling the trigger method to trigger the mouseout event. Calling the method with one or two parameters is the same as calling the
on method to establish an event handler for the elements in the set. The data argument gets relayed to the event handler via the event.data property, and the handler argument is a reference
to the event handler function.
For an example, please refer to the example for the similar blur method.
The mouseover method establishes an event handler for the mouseover event, or triggers the same event. The method signature is jQuerySet.mouseover([/*any*/ data] [,/*function*/ handler])
and it returns the jQuery set that
it is called on. Calling the method with no parameters is equivalent to calling the trigger method to trigger the mouseover event. Calling the method with one or two parameters is the same as calling the
on method to establish an event handler for the elements in the set. The data argument gets relayed to the event handler via the event.data property, and the handler argument is a reference
to the event handler function.
For an example, please refer to the example for the similar blur method.
The mouseup method establishes an event handler for the mouseup event, or triggers the same event. The method signature is jQuerySet.mouseup([/*any*/ data] [,/*function*/ handler])
and it returns the jQuery set that
it is called on. Calling the method with no parameters is equivalent to calling the trigger method to trigger the mouseup event. Calling the method with one or two parameters is the same as calling the
on method to establish an event handler for the elements in the set. The data argument gets relayed to the event handler via the event.data property, and the handler argument is a reference
to the event handler function.
For an example, please refer to the example for the similar blur method.
The ready method establishes an event handler for the ready event, or triggers the same event. The method signature is jQuerySet.ready([/*any*/ data] [,/*function*/ handler])
and it returns the jQuery set that
it is called on. Calling the method with no parameters is equivalent to calling the trigger method to trigger the ready event. Calling the method with one or two parameters is the same as calling the
on method to establish an event handler for the elements in the set. The data argument gets relayed to the event handler via the event.data property, and the handler argument is a reference
to the event handler function.
For an example, please refer to the example for the similar blur method.
The resize method establishes an event handler for the resize event, or triggers the same event. The method signature is jQuerySet.resize([/*any*/ data] [,/*function*/ handler])
and it returns the jQuery set that
it is called on. Calling the method with no parameters is equivalent to calling the trigger method to trigger the resize event. Calling the method with one or two parameters is the same as calling the
on method to establish an event handler for the elements in the set. The data argument gets relayed to the event handler via the event.data property, and the handler argument is a reference
to the event handler function.
For an example, please refer to the example for the similar blur method.
The scroll method establishes an event handler for the scroll event, or triggers the same event. The method signature is jQuerySet.scroll([/*any*/ data] [,/*function*/ handler])
and it returns the jQuery set that
it is called on. Calling the method with no parameters is equivalent to calling the trigger method to trigger the scroll event. Calling the method with one or two parameters is the same as calling the
on method to establish an event handler for the elements in the set. The data argument gets relayed to the event handler via the event.data property, and the handler argument is a reference
to the event handler function.
For an example, please refer to the example for the similar blur method.
The select method establishes an event handler for the select event, or triggers the same event. The method signature is jQuerySet.select([/*any*/ data] [,/*function*/ handler])
and it returns the jQuery set that
it is called on. Calling the method with no parameters is equivalent to calling the trigger method to trigger the select event. Calling the method with one or two parameters is the same as calling the
on method to establish an event handler for the elements in the set. The data argument gets relayed to the event handler via the event.data property, and the handler argument is a reference
to the event handler function.
For an example, please refer to the example for the similar blur method.
The submit method establishes an event handler for the submit event, or triggers the same event. The method signature is jQuerySet.submit([/*any*/ data] [,/*function*/ handler])
and it returns the jQuery set that
it is called on. Calling the method with no parameters is equivalent to calling the trigger method to trigger the submit event. Calling the method with one or two parameters is the same as calling the
on method to establish an event handler for the elements in the set. The data argument gets relayed to the event handler via the event.data property, and the handler argument is a reference
to the event handler function.
For an example, please refer to the example for the similar blur method.
A common pattern is to update the UI in some way when the mouse pointer is over an element. This is often used, for example, in dropdown menus or with buttons. To implement this, one would normally respond to the mouseenter event
that is triggered when the pointer moves into an element and the mouseleave, fired when the pointer moves out again. Instead of using the on method to do this,
jQuery offers a condensed way of setting up such handlers through the hover method. Calling that method
sets up event handlers for the two event types for the elements in the set that the method is called on. It has the signature jQuerySet.hover(/*function*/ handler1 [,/*function*/ handler2])
and returns a reference to the same jQuery set.
When only one handler is specified, it becomes the handler for both the mouseenter and mouseleave events. When two handlers are specified, the first one is for the mouseenter and the second one for the mouseleave event.
The following example changes the color of buttons to red when the mouse hovers over them, and back to green when the mouse leaves:
<button style="background-color:green;">Button A</button>
<button style="background-color:green;">Button B</button>
<script>
jQuery("button").hover(
function (event) {
jQuery(event.target).css("background-color", "red");
},
function (event) {
jQuery(event.target).css("background-color", "green");
}
);
</script>