jQuery .on() and .off()

The new .on() and .off() APIs unify all the ways of attaching events to a document in jQuery: bind, unbind, delegate, undelegate, live, die - which are now deprecated.

<script>
$(elements).on( events [, selector] [, data] , handler );
$(elements).off( [ events ] [, selector] [, handler] );
</script>

When a selector is provided, .on() is similar to .delegate() in that it attaches a delegated event handler, filtered by the selector. When the selector is omitted or null the call is like .bind().

<script>
$('a').bind('click', myHandler); // old
$('a').on('click', myHandler); // new
 
$('form').bind('submit', { val: 42 }, fn); // old
$('form').on('submit', { val: 42 }, fn); // new
 
$(window).unbind('scroll.myPlugin'); // old
$(window).off('scroll.myPlugin'); // new
 
$('.comment').delegate('a.add', 'click', addNew); // old
$('.comment').on('click', 'a.add', addNew); // new
 
$('.dialog').undelegate('a', 'click.myDlg'); // old
$('.dialog').off('click.myDlg', 'a'); // new
 
$('a').live('click', fn); // old
$(document).on('click', 'a', fn); // new
 
$('a').die('click'); // old
$(document).off('click', 'a'); // new
 
 
$('.target').on('click', function() {
	console.log('clicked');
});
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *