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);
$('a').on('click', myHandler);
 
$('form').bind('submit', { val: 42 }, fn);
$('form').on('submit', { val: 42 }, fn);
 
$(window).unbind('scroll.myPlugin');
$(window).off('scroll.myPlugin');
 
$('.comment').delegate('a.add', 'click', addNew);
$('.comment').on('click', 'a.add', addNew);
 
$('.dialog').undelegate('a', 'click.myDlg');
$('.dialog').off('click.myDlg', 'a');
 
$('a').live('click', fn);
$(document).on('click', 'a', fn);
 
$('a').die('click');
$(document).off('click', 'a');
</script>

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">