I see there's a new method .on()
in jQuery 1.7 that replaces the .live()
in earlier versions.
I'm interested to know the difference between them and what the benefits are of using this new method.
I see there's a new method .on()
in jQuery 1.7 that replaces the .live()
in earlier versions.
I'm interested to know the difference between them and what the benefits are of using this new method.
One difference that people stumble on when moving from
.live()
to.on()
is that the parameters for.on()
are slightly different when binding events to elements added dynamically to the DOM.Here's an example of the syntax we used to use with the
.live()
method:Now with
.live()
being deprecated in jQuery version 1.7 and removed in version 1.9, you should use the.on()
method. Here's an equivalent example using the.on()
method:Please note that we're calling
.on()
against the document rather than the button itself. We specify the selector for the element whose events we're listening to in the second parameter.In the example above, I'm calling
.on()
on the document, however you'll get better performance if you use an element closer to your selector. Any ancestor element will work so long as it exists on the page before you call.on()
.This is explained here in the documentation but it is quite easy to miss.
It's pretty clear in the docs why you wouldn't want to use live. Also as mentioned by Felix,
.on
is a more streamline way of attaching events.This method is used to attach an event handler for all elements which match the current selector, now and in the future.
and
This method is used to attach an event handler function for one or more events to the selected elements below is the example.
I have a requirement to identify browser closed event. After Doing to of research I am doing following using jQuery 1.8.3
Turn ON a flag using following jQuery when hyperlink is clicked
$('a').live('click', function() {cleanSession = false;});
Turn ON a flag using following jQuery when any time input button type of submit is clicked
$("input[type=submit]").live('click',function(){alert('input button clicked');cleanSession=false;});
$('form').live('submit', function() {cleanSession = false;});
Now important thing...my solution only works if I use .live instead .on. If I use .on then the event gets fired after form gets submitted and which is too late. Many times my forms gets submitted using javascript call (document.form.submit)
So there is a key difference between .live and .on . If you use .live your events get fired immediately but if you switch to .on it doesn't get fired on time
See the official Blog
for more info check it out.. .live() and .on()
.live() method is used when you deal with the dynamic generation of contents... like I have created on program that adds a tab when i change the value of a Jquery Slider and I want to attach the close button functionality to every tabs which will generated... the code i have tried is..
and it works preety much cool...