jQuery 1.7 introduced new methods for handling DOM events in JavaScript; on()
and off()
. In this article we will focus on on()
.
It is intended that, from now on, on()
should be used where you’d previously have used any of bind()
, live()
, delegate()
. In particular, live()
has been depreciated already; so usage of this in your projects should cease immediately. Converting from any of these methods to on()
is easy; you just have to follow the following conversion rules:
-
If you were previously using
bind()
, simply change the function name toon()
;on()
supports the same method signatures asbind()
.$('.foo').bind('click', function () { alert('Hello'); })`;
… will now be…
$('.foo').on('click', function () { alert('Hello'); });
-
If you were previously using
delegate(selector, map)
, whereselector
identified the elements whose events you wanted to handle, andmap
was an object which mapped event types to handlers, swap theselector
andmap
arguments around.$('div').delegate('a', { mouseover: function () { alert('Mouse Over!')' }, mouseleave: function () { alert('Mouse Out!')' } });
… will now be…
$('div').on({ mouseover: function () { alert('Mouse Over!')' }, mouseleave: function () { alert('Mouse Out!')' } }, 'a');
-
All other uses of
delegate()
can be converted toon()
by swapping the order of the first two parameters (the selector and event list)$('div').delegate('a', 'click', function () { alert('Clicked!'); });
… will now be…
$('div').on('click', 'a', function () { alert('Clicked!'); });
-
All uses of
live()
can be converted to useon()
by inserting the selector as the second argument toon()
, and setting what-used-to-be-the-selector todocument
:$('a').live('click', function () { alert('Clicked!'); });
… will now be…
$(document).on('click', 'a', function () { alert('Clicked!'); });
.. and that’s all there is to it! To find out more about the new function on()
, you can read it’s extensive documentation on the jQuery website.