jQuery Events Attach and Detach Event Handlers


Example

Attach an Event Handler

Since version 1.7 jQuery has the event API .on(). This way any standard javascript event or custom event can be bound on the currently selected jQuery element. There are shortcuts such as .click(), but .on() gives you more options.


HTML

<button id="foo">bar</button>

jQuery

$( "#foo" ).on( "click", function() {
  console.log( $( this ).text() ); //bar
});

Detach an Event Handler

Naturally you have the possibility to detach events from your jQuery objects too. You do so by using .off( events [, selector ] [, handler ] ).


HTML

<button id="hello">hello</button>

jQuery

$('#hello').on('click', function(){
    console.log('hello world!');
    $(this).off();
});

When clicking the button $(this) will refer to the current jQuery object and will remove all attached event handlers from it. You can also specify which event handler should be removed.

jQuery

$('#hello').on('click', function(){
    console.log('hello world!');
    $(this).off('click');
});

$('#hello').on('mouseenter', function(){
    console.log('you are about to click');
});

In this case the mouseenter event will still function after clicking.