.on()
S2C Home « Events « .on()
Event handler attachment.
Description
The .on()
method is used to attach an event handler for the given event type(s), optionally passing a selector and/or a map of data.
- Starting with jQuery version 1.7 the
.on()
method provides all functionality required for attaching events to event handlers. The.on()
method allows us to attach event handlers directly to a document and is the preferred method to use. Where the version allows it always use the.on()
method instead of the older event attachment methods.bind()
,.delegate()
and.live()
. - Events attached with the
.on()
method can be unattached by using the.off()
method. - When you want a handler to execute once only and then unattach itself use the
.one()
method instead of the.on()
method. - A requirement of the jQuery's event system is that a DOM element allows attachment of data via a property on the element, allowing events to be tracked and delivered. For this reason the
object
,embed
, andapplet
elements which cannot have data attached to them, cannot have jQuery events bound to them. - When an event is triggered by the browser or an event is triggered from other JavaScript code by calling the
.trigger()
method, jQuery passes the handler a
object. ThejQuery.Event
object can be used to investigate and modify the status of the event. ThejQuery.Event
object includes a normalized subset of data provided by the browser. The browser's unmodified native event object is available injQuery.Event
event.originalEvent
- When jQuery calls a handler, the
this
special operator is a reference to the element where the event is being delivered and is used with jQuery methods using$(this)
:- For directly-bound event handlers ( when the
selector
parameter is omitted or isnull
) - thethis
special operator refers to the element where the event was attached. - For delegated event handlers ( when the
selector
parameter is present ) - thethis
special operator refers to an element matching theselector
parameter. This may not be equal to theevent.target
property if the event has bubbled up from a descendant element.
- For directly-bound event handlers ( when the
- By default, most events bubble up from the original event target to the
document
element with the following exceptions:- As specified by the W3C the
focus
andblur
events do not bubble up from the original event target to thedocument
element. However jQuery defines the cross-browser functional.focusin()
and.focusout()
events that do bubble. When thefocus
andblur
events are used to attach delegated event handlers, the names are mapped by jQuery and delivered as the.focusin()
and.focusout()
events respectively. So best practice is to use the.focusin()
and.focusout()
events. - The
.load()
event does not bubble in any browser. In Internet Explorer versions prior to 9, thepaste
andreset
events do not bubble. These events are not supported for use with event delegation, but can be used when the event handler is directly attached to the element generating the event. - The
Window
objecterror
event uses non-standard arguments and return value conventions and is not supported by jQuery. If you need to use this event then assign a handler function directly to thewindow.onerror
property.
- As specified by the W3C the
- When an event reaches an element, all handlers bound to that event type for the element are fired. If multiple handlers are registered for the element, they will always execute in the order in which they
were bound. When all handlers have finished executing, the event continues along the normal event propagation path.
- A handler can prevent the event from bubbling further up the document tree, thus preventing handlers on those elements from running, by calling the
event.stopPropagation()
method. - If other handlers are attached to the current element these will run however. This can be prevented by calling the
event.stopImmediatePropagation()
method. - To cancel any default action that the browser may have for this event, call the
event.preventDefault()
method. - Returning
false
from an event handler or calling an event handler with thefalse
parameter, as an example ($('aSelector').on('anEventType', false);
) will automatically call theevent.stopPropagation()
andevent.preventDefault()
methods on it.
- A handler can prevent the event from bubbling further up the document tree, thus preventing handlers on those elements from running, by calling the
Syntax
Signature | Description |
---|---|
.on( events [, selector] [, data], handler(eventObject) ) | Attach event handlers for the given String of event type(s), optionally passing a selector and/or an object of data. |
.on( events [, selector] [, data] ) | Attach event handlers for the given PlainObject of event type(s), optionally passing a selector and/or an object of data. |
Parameters
Parameter | Description | Type |
---|---|---|
events | A String or PlainObject containing one or more DOM event types or custom event names.
| String or PlainObject |
selector | A string containing a CSS or custom jQuery selector to filter the elements that trigger the events.
| String |
data | An object or map of key-value pair data which can be any type. If this optional parameter is provided and is not null or
undefined , it will be passed to the event handler via event.data property when the event occurs.
| Anything |
handler( eventObject [, Anything extraParameter ] [, ... ] ) | A function to execute each time the event is triggered or false . | Function |
events | An object of key-value pair data of event type(s) and handlers. | PlainObject |
Return
A jQuery
object.
.on(events[,selector][,data],handler(eventObject))
ExamplesTop
Attach an event handler for the given String
of event type(s) ( direct event handler).
When we press the mouse button the click
JavaScript event is fired and we output a message.
$(function(){
$('#btn6').on('click', function(){
$('#scrollspan1').append('** The JavaScript "click" event triggered for button **');
});
});
We will show a message here for the mouse button presses.
Attach an event handler for the given String
of event type(s) passing a selector ( delegated event handler).
When we press the mouse button the click
JavaScript event is fired for the specified selector and we output a message.
$(function(){
$('form').on('click', '#btn7', function(){
$('#scrollspan2').append('** The JavaScript "click" event triggered for button **');
});
});
We will show a message here for mouse button presses.
Attach an event handler for the given String
of event type(s), passing a selector and a map of data ( delegated event handler).
In the next example we use all of the the .on()
methods parameters and pass an object of data to the addText()
function, which outputs a message below.
What we are doing here is passing across the event
object to the function addText(event)
. The object map we specify, in our case { param1: '#scrollspan3', param2: 'click was attached from on', param3: '**JavaScript event triggered** ' }
gets tagged onto the event.data
property. We then access these parameter in the function via event.data.param
and use it as part of the appended data.
$(function(){
$('form').on('click', '#btn8',
{ param1: '#scrollspan3', param2: 'click was attached from .on() ',
param3: '**JavaScript event triggered** ' }, addText);
function addText(event) {
$(event.data.param1).append(event.data.param2 + '<code>' + event.data.param3+ '</code>');
}
});
We will show a message here.
In the next example we use all of the the .on()
methods parameters and pass a custom jQuery.Event
object (ourEvent) to
the addText()
function, which outputs a message below.
What we are doing here is passing across our custom event
object to the function addText(event)
. The parameters we specified for our custom event object get tagged onto the
event.data
property. We then access these parameters in the function and use it as part of the appended data.
This is a cleaner approach than passing a map of data as in the previous example. Imagine what the passed parameter code would look like when you were passing across many parameters. Also think about maintainability and how this approach makes maintaining the code much easier.
$(function(){
var ourEvent = $.Event('click.ns1');
ourEvent.param1 = '#scrollspan4';
ourEvent.param2 = 'click was attached from .on() ';
ourEvent.param3 = '**JavaScript event triggered** using custom object and namespace ';
$('form').on('click.ns1', '#btn9', ourEvent, addText);
function addText(event) {
$(event.data.param1).append(event.data.param2 + '<code>' + event.data.param3+ '</code>');
}
});
We will show a message here.
.on(events[,selector] [,data], handler(eventObject [, Anything extraParameter ] [, ... ] )
ExamplesTop
Attach a PlainObject
of event type(s) and handlers ( direct event handler).
In the example below when you enter or leave the 'div4' element the mouseenter
and mouseleave
JavaScript events fire.
$(function(){
$('#div4').on({
'mouseenter.ns4': function(ourEvent) {
$(this).css({backgroundColor: 'orange', color: 'black'})
.append('**entering "div4". Event param : ' + ourEvent.param);
},
'mouseleave.ns4': function() {
$(this).css({backgroundColor: 'red', color: 'white'})
.append('**leaving "div4" ');
}
});
});
Some initial text.
Attach a PlainObject
of of event type(s) and handlers, passing a selector ( delegated event handler).
In the example below when you enter or leave the 'para1' element the mouseenter
and mouseleave
JavaScript events fire. When this happens our custom event-types and their handlers are executed.
$(function(){
$('#div5').on({'mouseenter.ns5': ourHandler1}, '#para1');
$('#div5').on({'mouseleave.ns5': ourHandler2}, '#para1');
function ourHandler1() {
$(this).css({backgroundColor: 'yellow', color: 'black'})
.append('**entering "div5. "');
}
function ourHandler2() {
$(this).css({backgroundColor: 'teal', color: 'white'})
.append('**leaving "div5. "');
}
});
para1. Some initial text.
Attach a PlainObject
of object of event type(s) and handlers, passing a selector and a map of data ( delegated event handler).
In the example below when you enter or leave the 'para2' element the mouseenter
and mouseleave
JavaScript events fire. When this happens our custom event-types and their handlers are
executed. The parameters we specified get tagged onto the event.data
property. We then access these parameters in the function addText
and
output a message.
$(function(){
$('#div6').on({'mouseenter.ns6': ourHandler3}, '#para2',
{ param1: '#scrollspan5', param2: 'mouseenter was attached from .on() ',
param3: '**JavaScript event triggered** ' });
$('#div6').on({'mouseleave.ns6': ourHandler4}, '#para2',
{ param1: '#scrollspan5', param2: 'mouseleave was attached from .on() ',
param3: '**JavaScript event triggered** ' });
function ourHandler3(event) {
$(this).css({backgroundColor: 'lime', color: 'black'})
.append('**entering "div6. "');
addText(event);
}
function ourHandler4(event) {
$(this).css({backgroundColor: 'silver', color: 'white'})
.append('**leaving "div6. "');
addText(event);
}
function addText(event) {
$(event.data.param1).append(event.data.param2 + '' + event.data.param3 + '
');
}
});
para2. Some initial text.
We will show a message here.
In the example below when you enter or leave the 'para3' element the mouseenter
and mouseleave
JavaScript events fire. When this happens our custom event-types and their handlers are
executed. We also pass a custom jQuery.event
object (ourEvent2).
What we are doing here is passing across our custom event
object to our handlers, which then gets passed to the addText(event)
function. The parameters we specified for our custom event
object get tagged onto the event.data
property. We then access these parameters in the addText(event)
function and use it as part of the appended data.
This is a cleaner approach than passing a map of data as in the previous example and makes code maintainance much easier.
$(function(){
var ourEvent2 = $.Event('mouseenter.ns7 mouseleave.ns7');
ourEvent2.param1 = '#scrollspan6';
ourEvent2.param2 = 'events were attached from .on() ';
ourEvent2.param3 = '**JavaScript event triggered** using custom object and namespace ';
$('#div7').on({'mouseenter.ns7': ourHandler3}, '#para3', ourEvent2);
$('#div7').on({'mouseleave.ns7': ourHandler4}, '#para3', ourEvent2);
function ourHandler3(event) {
$(this).css({backgroundColor: 'lime', color: 'black'})
.append('**entering "div6. "');
addText(event);
}
function ourHandler4(event) {
$(this).css({backgroundColor: 'red', color: 'white'})
.append('**leaving "div6. "');
addText(event);
}
function addText(event) {
$(event.data.param1).append(event.data.param2 + '' + event.data.param3 + '
');
}
});
para3. Some initial text.
We will show a message here.
Related Tutorials
jQuery Advanced Tutorials - Lesson 4 - Event Handler Attachments