Event Handler AttachmentsS2C Home « Event Handler Attachments

Following on from our three lessons covering all the JavaScript event handler methods in jQuery, we delve into the event handler attachments available for use with these events.

These are some of the most powerful methods in the jQuery library and give us complete control of event handling.

  • Starting with jQuery version 1.7 more flexible event binding can be achieved using the .on() method. The .on() method allows us to attach event handlers directly to a document and is the preferred method to use when using this version onwards.
  • 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.
Event Handler Attachment Methods Description
.bind() **DEPRECATED**
Bind an event handler to the specified elements.
.delegate() **DEPRECATED**
Henceforth, bind an event handler to all elements matching the specified selector, dependant upon a specific set of root elements.
.die() **REMOVED**
Remove all event handlers from elements previously attached using .live().
.live() **REMOVED**
Henceforth, bind an event handler to all elements matching the specified selector.
.off()Remove an event handler from the specified events, selectors or previously attached handler function.
.on()Add an event handler for an event(s), selectors or handler function.
.one()Add an event handler for an event(s), data or eventObject that will execute a maximum of one times.
.jQuery.proxy() **DEPRECATED**
Return a new function with a particular context or set a context for a function.
.trigger()Manually fire all event handlers and behaviours on the matched set, for the specified event type.
.triggerHandler()Manually fire all event handlers and behaviours on an element of the matched set, for the specified event type.
.unbind() **DEPRECATED**
Unbind a previously bound event handler from the specified elements.
.undelegate() **DEPRECATED**
Unbind an event handler from all elements matching the specified selector, dependant upon a specific set of root elements.

Bind event handlers to the blur, change, focus, select and submit JavaScript events.

The .bind() Method     **DEPRECATED** Top

Bind an event handler to the specified elements.

  • The .bind() method attaches an event handler directly to the elements that are currently selected in the jQuery object, therefore the elements must exist when the call to the .bind() method happens.

We will be using the .bind( events ) signature for our example, which will bind an event handler to a specified map of event type(s) and functions to execute for them.

The second signature .bind( eventType [eventData ,] handler(eventObject) ) will bind an event handler to specified event type(s), optionally passing a map of data.

The third signature .bind( eventType [, eventData], preventBubble ) will bind an event handler to specified event type(s) with or without bubbling, optionally passing a map of data

Examples of these signatures are available in the reference section.

In the example below we pass a bind a map of event types and actions to perform when they are fired.

When we press the button with an id of 'btn4' the click JavaScript event fires and turns the background colour of this button to orange. When we move the mouse away from this button we fire off the mouseleave JavaScript event which in our case appends some text to a paragraph.


$(function(){
  $('#btn4').bind({
     click: function() {
       $(this).css('backgroundColor', 'orange');
     },
     mouseleave: function() {
       $('#scrollspan2').append('  leaving "btn4"  ');
     }
  });
});

Press the button below to action the above code:

We will show a message here.

The .delegate() Method     **DEPRECATED** Top

Henceforth, attach an event handler to all elements matching the specified selector for the given event type(s), based upon a specific set of root elements.

  • To remove events attached with the delegate() method, see the .undelegate() method.

We will be using the delegate( selector, eventType, handler(eventObject) ) signature for our example, which will henceforth, attach an event handler to all elements matching the specified selector for the given event type(s).

The second signature .delegate( selector, eventType, eventData, handler(eventObject) ) will henceforth, attach an event handler to all elements matching the specified selector for the given event type(s), passing a map of data.

The third signature .delegate(selector, events ) will henceforth, attach a map of event type(s) and functions to execute for them, for the specified selector.

Examples of these signatures are available in the reference section.

In the example below when we press the button we fire off the the event handler we attached to 'btn5' for the click JavaScript event and turn the background colour of this button to yellow.


$(function(){
  $('#main').delegate('#btn5', 'click', function() {
    $(this).css('backgroundColor', 'yellow');
  });
});

Press the button below to action the above code:

The .die() Method     **REMOVED** Top

Remove event handlers from elements that were previously attached using the .live() method.

This method was deprecated in jQuery 1.7 and removed in jQuery 3.5 and we are just showing it for completeness.

  • From jQuery version 1.7 onwards, use the .off() method to remove event handlers, that have been attached using the .on() method.

The .live()Method     **REMOVED** Top

Henceforth, attach an event handler to all elements matching the current selector for the given event type(s).

This method was deprecated in jQuery 1.7 and removed in jQuery 3.5 and we are just showing it for completeness.

  • From jQuery version 1.7 onwards, use the .on() method to attach event handlers.

The .off() Method Top

Remove event handlers for the given event type(s), optionally passing a selector.

  • The .off() method is used to remove an event handler attached using the .on() method. If multiple filtering arguments are specified for removal, these must match the parameters of a previously attached event handler for it to be removed.

We will be using a form of the .off( events [, selector] [, handler(eventObject)] ) signature for our example, which will remove event handlers for the given String of event type(s), optionally passing a selector and/or handler..

The second signature .off( events [, selector] ) will remove event handlers for the given PlainObject of event type(s), optionally passing a selector.

The third signature .off( event ) will remove all event handlers of given event type from attached elements.

The fourth signature .off() will remove all event handlers from attached elements.

Examples of all forms of these signatures are available in the reference section.

When we press the left button the mousedown and mouseup JavaScript events are fired and we output a message.

When we press the right button the first time, the click JavaScript event fires. When this event occurs we remove the mousedown and mouseup JavaScript event for 'btn1' and output a message. If you hit the left mouse button again you will see that all JavaScript event handlers do not fire anymore.


$(function(){
  $('#btn1').on('mousedown', ourHandler1);
  $('#btn1').on('mouseup', ourHandler2);
  $('#btn2').one('click', function(){
     $('#btn1').off('mousedown mouseup');
     $('#scrollspan1').append('** The JavaScript "mousedown" and "mousedup" events 
                               for "btn1" have been removed**');
  });

  function ourHandler1() {
    $('#scrollspan1').append('** The JavaScript "mousedown" event triggered for button **');
  }
  function ourHandler2() {
    $('#scrollspan1').append('** The JavaScript "mouseup" event triggered for button **');
  }
});

Press the button below to action the above code:

                     

We will show a message here for the mouse button presses.


The .on() Method  Top

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.

We will be using a form of the .on( events [, selector] [, data] ) signature for our example, which will attach event handlers for the given PlainObject of event type(s), optionally passing a selector and/or an object of data.

The second signature .on( events [, selector] [, data], handler(eventObject) ) will attach event handlers for the given String of event type(s), optionally passing a selector and/or an object of data.

Examples of all forms of these signatures are available in the reference section.

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.


$(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.


The .one() Method  Top

Attach an event handler for the given event type(s) that will execute a maximum of one times, optionally passing a selector and/or a map of data.

  • The .one() method is identical to the .on() method but will execute a maximum of one times and then unattach itself. Use the .on() method when you require mutiple event handler executions that stay attached.
  • See the reference description for the .on() method for details of jQuery eventing.

We will be using a form of the .one( events [, selector] [, data] ) signature for our example, which event handlers for the given PlainObject of event type(s), optionally passing a selector and/or an object of data.

The second signature .one( events [, selector] [, data], handler(eventObject) ) will event handlers for the given String of event type(s), optionally passing a selector and/or an object of data.

optionally passing a selector and/or a map of data.

Examples of all forms of these signatures are available in the reference section.

In the example below when you press the left mouse button down or release the left mouse button while the cursor is over the 'para1' element the mousedown and mouseup JavaScript events fire once only. When this happens our custom event-types and their handlers are executed.


$(function(){
  $('#div5').one({'mousedown.ns5': ourHandler5}, '#para1');
  $('#div5').one({'mouseup.ns5': ourHandler6}, '#para1');

  function ourHandler5() {
    $(this).css({backgroundColor: 'yellow', color: 'black'})
           .append('**mousedown "div5. "');
  }
  function ourHandler6() {
    $(this).css({backgroundColor: 'teal', color: 'white'})
           .append('**mouseup "div5. "');
  }
});

para1. Some initial text.



The jQuery.proxy() Method  Top

Return a new function with a particular context or set a context for a function.

  • The jQuery.proxy() method is used to preserve a reference to the calling object when the value of the this special operator is changed.
  • After using thejQuery.proxy() method the this special operator is changed to our context. This means that the DOM element that actually triggered the event can no longer be accessed using the this special operator. We can still access this triggering DOM element using the event.currentTarget property of the jQuery.event object.
  • When jQuery attaches an event handler, a unique id is assigned to the handler function, therefore a handler can also be removed by specifying the function name in the handler argument. Handlers proxied by the jQuery.proxy() method or similar mechanisms will all have the same unique id. In this case passing proxied handlers to the .off() method may remove more handlers than required. Adding namespaces when attaching or removing event handlers gets around this issue and is a good practice to use anyway.

We will be using the jQuery.proxy( function, context ) signature for our example, which will return a new function with a particular context.

The second signature jQuery.proxy( context, name ) will set a context for a function.

Examples of these signatures are available in the reference section.

In the example below when we press the left button the click JavaScript event fires and we try to output this.msg from the aFunction.prototype.processClick = function() {} function. But this.msg will be undefined as the triggering event takes the scope of the this special operator.

When we press the right button, the click JavaScript event fires and passes across the current scope as our context to the bFunction.prototype.processClick = function() {} function. So When we access this.msg from the proxied function it is still in scope and an output message is rendered. We can still access this triggering DOM element using the event.currentTarget property of the jQuery.event object.



$(function(){
  aFunction = function() {
    this.$btn = $('#btn9');
    this.msg = 'A message to pass for testing from "btn9" click';
    this.$btn.click(this.processClick);
  };
  aFunction.prototype.processClick = function(event) {
    $('#scrollspan4').append(this.msg + ' Triggering element was: ' 
                                      + event.currentTarget + ' ** '); 
  };

  bFunction = function() {
    this.$btn = $('#btn10');
    this.msg = 'A message to pass for testing from "btn9" click';
    this.$btn.click($.proxy(this.processClick, this));
  };
  bFunction.prototype.processClick = function(event) {
    $('#scrollspan4').append(this.msg + ' Triggering element was: ' 
                                      + event.currentTarget + ' ** '); 
  };

  var aVar = new aFunction();
  var bVar = new bFunction();
});

Press the button below to action the above code:

                     

We will show a message here for the mouse button presses.


The .trigger() Method  Top

Manually fire all event handlers and behaviours on the matched set, for the specified event type.

We will be using the .trigger( events ) signature for our example, which will manually fire a specified map of event type(s) and functions to execute for them.

The second signature .trigger( eventType [, extraParameters] ) will manually fire all event handlers and behaviours on the matched set, for the specified event, optionally passing parameters..

Examples of all forms of these signatures are available in the reference section.

In the example below when you enter or leave the 'div2' element the mouseenter and mouseleave JavaScript events fire. The parameter passed is undefined as this is only triggered from the button click.

When we press the button we manually create a custom jQuery.event object (ourEvent). This is equivalent to typing  {type:'mouseenter.ns2',param:'passed param'}; within the call to the .trigger() method but in a cleaner way. The type property indicates the kind of event being raised. We then trigger the mouseenter JavaScript event on 'div2' passing across our custom event object. Now we see our passed parameter value of 'passed param' instead of 'undefined'.


$(function(){
  $('#div2').on({
     'mouseenter.ns2': function(ourEvent) {
       $(this).css({backgroundColor: 'yellow', color: 'black'})
              .append('**entering "div2". Event param : ' + ourEvent.param);
     },
     'mouseleave.ns2': function() {
       $(this).css({backgroundColor: 'red', color: 'white'})
              .append('**leaving "div2"  ');
     }
  });
  $('#btn3').on('click', function(){
     var ourEvent = $.Event('mouseenter.ns2');
     ourEvent.param = 'passed param';
     $('#div2').trigger(ourEvent);
  });
});

div2. Some initial text.



Press the button below to action the above code:

The .triggerHandler() Method  Top

Manually fire all event handlers and behaviours on the matched set, for the specified event type.

We will be using this methods .triggerHandler( eventType [, extraParameters] ) signature for our example, which will manually fire all event handlers on an element, for the specified event type, optionally passing parameters.

The second signature .triggerHandler( event [, extraParameters] ) will manually fire all event handlers on an element, for the specified event, optionally passing parameters.

Examples of all forms of these signatures are available in the reference section.

In the example below when you enter or leave the 'div3' element the mouseenter and mouseleave JavaScript events fire.

When we press the left button we triggerHandler the mouseenter JavaScript event manually. We are not passing across a parameter for any events so the output contains 'undefined' for the param parameter.

When we press the right button we triggerHandler the mouseenter JavaScript event manually. We are passing across the string '**PASSED PARAM**' for the param parameter, so the output message will contain this when fired from the triggerHandler or 'undefined' otherwise.


$(function(){
  $('#div3').on({
     'mouseenter.ns3': function(event, param) {
       $(this).css({backgroundColor: 'teal', color: 'black'})
              .append('**entering "div3". Passed param : ' + param);
     },
     'mouseleave.ns3': function() {
       $(this).css({backgroundColor: 'maroon', color: 'white'})
              .append('**leaving "div3"  ');
     }
  });
  $('#btn6').on('click', function(){
     $('#div3').triggerHandler('mouseenter.ns3');
  });
  $('#btn7').on('click', function(){
     $('#div3').triggerHandler('mouseenter.ns3', '**PASSED PARAM**');
  });
});

div3. Some initial text.



Press the button below to action the above code:

             

The .unbind() Method     **DEPRECATED** Top

Unattach a previously bound event handler(s) from the specified elements.

  • The .unbind() method unattaches event handlers previously attached using the .bind() method.
  • Starting with jQuery version 1.7, more flexible event binding and unbinding can be achieved using the .on() and .off() methods. The .on() method allows us to attach event handlers directly to a document and is the preferred method to use when using this version onwards.

We will be using the .unbind( event ) signature for our example, which will unbind a JavaScript event object that was previously passed to an event handler.

The second signature .unbind( [eventType], [handler(eventObject)] ) will unbind all event handlers from the specified elements, optionally passing a specified event type(s) and/or event handlers, to filter the unbinding.

The third signature .unbind( eventType, false ) will unbind the corresponding return false function that was bound using .bind( eventType, false ).

The fourth signature .unbind( namespace ) will unbind all events for a namespace.

Examples of all forms of these signatures are available in the reference section.

In the example below we unbind the event object from the button below with an id of 'btn13' after the click JavaScript event has been fired three times. We then turn the background colour of this button to green and append a final message to the paragraph below.


$(function(){
  var clickCount = 0;
  $('#btn13').bind('click', function(event) {
    clickCount++;
    if (clickCount < 3) {
        $('#scrollspan8').append('**"click" pressed for this button: ' 
        + clickCount + ' times ** ');
    } else {
        $('#scrollspan8').append('**"click" pressed for this button: ' + clickCount 
        + ' times ** and the event object has now been unbound');
        $(this).css('backgroundColor', 'green').unbind(event);
    }
  });
;});

Press the button below to action the above code:

We will show a message here.

The .undelegate() Method     **DEPRECATED** Top

Remove all event handlers for all elements matching the specified selector for the given event type(s), based upon a specific set of root elements.

  • The .undelegate() method unattaches event handlers previously attached using the .delegate() method.
  • Starting with jQuery version 1.7 more flexible event delegation can be achieved by using the .on() and .off() methods. The .on() method allows us to attach event handlers directly to a document and is the preferred method to use when using this version onwards.

We will be using the .undelegate( selector, events ) signature for our example, which will unattach from a map of event type(s) and previously bound functions.

The second signature .undelegate() will unattach all event handlers.

The third signature .undelegate( selector, eventType ) will unattach all elements matching the specified selector for the given event type

The fourth signature .undelegate( selector, eventType, handler(eventObject) ) will unattach an event handler for all elements matching the specified selector for the given event type.

The fifth signature .undelegate( namespace ) will unattach all events for a namespace.

Examples of these signatures are available in the reference section.

In this example we attach a map of event types to the table elements below and actions to perform when they are fired. When we press the button with an id of 'btn20' the click JavaScript event fires and we append some text to a paragraph and use a map to turn off the events and functions tied to the table elements. Mouseover and leave the table elements after clicking the button to see the effect of the undelegate

Table For Testing The .delegate( events ) Signature
Table Row 1, Table Data 1 Table Row 1, Table Data 2
Table Row 2, Table Data 1 Table Row 2, Table Data 2


$(function(){
  var ourHandler4 = function() {
    $(this).css('backgroundColor', 'orange');
    $('#scrollspan15').append('**entering ".testtable td"');
  };
  var ourHandler5 = function() {
    $(this).css('backgroundColor', 'olive');
    $('#scrollspan15').append('**leaving ".testtable td"');
  };
  $('#table1').delegate('td', 'mouseenter', ourHandler4);
  $('#table1').delegate('td', 'mouseleave', ourHandler5);
  $('#btn20').click(function(){
    $('#table1').undelegate('td', {mouseenter: ourHandler4, mouseleave: ourHandler5});
    $('#scrollspan15').append('**mouseenter/mouseleave events undelegated for ".testtable td"');
  });
});

Press the button below to action the above code:

We will show a message here.


Lesson 4 Complete

In this lesson we looked at the powerful event handler attachments we can use with events.

Related Tutorials

jQuery Advanced - Lesson 1: Browser & Loading Events
jQuery Advanced - Lesson 2: Keyboard & Mouse Events
jQuery Advanced - Lesson 3: Form Events
jQuery Advanced - Lesson 5: The Event Object

What's Next?

In the next lesson we look at the jQuery.Event object provided by jQuery.