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.
<button id="foo">bar</button>
$( "#foo" ).on( "click", function() {
console.log( $( this ).text() ); //bar
});
Naturally you have the possibility to detach events from your jQuery objects too. You do so by using .off( events [, selector ] [, handler ] )
.
<button id="hello">hello</button>
$('#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.
$('#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.