.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, and applet 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 jQuery.Event object. The jQuery.Event object can be used to investigate and modify the status of the event. The jQuery.Event object includes a normalized subset of data provided by the browser. The browser's unmodified native event object is available in 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):
    1. For directly-bound event handlers ( when the selector parameter is omitted or is null ) - the this special operator refers to the element where the event was attached.
    2. For delegated event handlers ( when the selector parameter is present ) - the this special operator refers to an element matching the selector parameter. This may not be equal to the event.target property if the event has bubbled up from a descendant element.
  • 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 and blur events do not bubble up from the original event target to the document element. However jQuery defines the cross-browser functional .focusin() and .focusout() events that do bubble. When the focus and blur 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, the paste and reset 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 object error 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 the window.onerror property.
  • 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 the false parameter, as an example ( $('aSelector').on('anEventType', false); ) will automatically call the event.stopPropagation() and event.preventDefault() methods on it.

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
eventsA String or PlainObject containing one or more DOM event types or custom event names.
  • If the String or PlainObject used for eventType is not the name of a native DOM event, the handler is bound to a custom event. Custom events are never called by the browser, but can be triggered manually from other JavaScript code using the .trigger() method.
  • If a period (.) character is present anywhere in the eventType string, then that event becomes namespaced. The characters before the period (.) character represent the eventType, whilst the characters after the period (.) character represent the namespace. As an example .on('anEventType.aNamespace', handler) could be used to handle some events whilst not affecting events for .on('anEventType.aNamespace2', handler). In essence, namespacing allows us to action certain events for an eventType without affecting other events for that eventType.
String or PlainObject
selectorA string containing a CSS or custom jQuery selector to filter the elements that trigger the events.
  • When the selector parameter is omitted or is null, the event handler is referred to as direct or directly-bound. The handler is called every time an event occurs on the selected elements, whether occuring directly on the element or bubbling up from a descendant element.
    • Event handlers are bound to the currently selected elements and therefore must exist on the page at the time the call to the .on() method is made. To ensure the elements are present and can be selected, perform event binding inside a document ready handler ( .ready() ) method for elements within the HTML markup on the page. For new HTML that is being created the page, select the elements and attach event handlers after the new HTML is present, or use delegated events to attach an event handler
  • When the selector parameter is present, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants matching the specifed selector parameter. jQuery bubbles the event from the event target up to the element where the handler is attached and runs the handler for any elements along that path matching the specifed selector parameter.
    • Delegated events have the advantage of being able to process events from descendant elements that are added to the document in the future. By selecting an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. The document element is available in the head of the document before loading any other HTML, so is a safe place to attach events without waiting for the document to be ready.
String
dataAn 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.
  1. If passing this parameter as a string the selector argument must be provided or explicitly passed as null so that the data argument is not mistaken for the selector argument.
  2. Where possible use an object (map) for this parameter so that multiple values can be passed as properties.
Anything
handler( eventObject [, Anything extraParameter ] [, ... ] )A function to execute each time the event is triggered or false.Function
eventsAn 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 **');
  });
});

Press the button below to action the above code:

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 **');
  });
});

Press the button below to action the above code:

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>');
  }
});

Press the button below to action the above 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>');
  }
});

Press the button below to action the above 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 addTextand 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.