85

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.

ajbeaven
  • 8,509
  • 11
  • 74
  • 109

8 Answers8

99

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.

Use of the .live() method is no longer recommended since later versions of jQuery offer better methods that do not have its drawbacks. In particular, the following issues arise with the use of .live():

  • jQuery attempts to retrieve the elements specified by the selector before calling the .live() method, which may be time-consuming on large documents.
  • Chaining methods is not supported. For example, $("a").find(".offsite, .external").live( ... ); is not valid and does not work as expected.
  • Since all .live() events are attached at the document element, events take the longest and slowest possible path before they are handled.
  • Calling event.stopPropagation() in the event handler is ineffective in stopping event handlers attached lower in the document; the event has already propagated to document.
  • The .live() method interacts with other event methods in ways that can be surprising, e.g., $(document).unbind("click") removes all click handlers attached by any call to .live()!
aziz punjani
  • 24,673
  • 9
  • 42
  • 56
  • 8
    Just wondering, if this is the point why don't they improved the live method instead of create a new on method. Unless there is something live can do but not on? – neobie Oct 06 '12 at 03:27
  • 1
    @neobie, Its for making your code more meaningful, and have uniformity – Om Shankar Feb 26 '13 at 17:51
  • @neobie: I imagine it's to maintain backwards compatibility. The differences pointed out in this answer show how their behavior is slightly different. If `live()` were modified to have the behavior of `on()`, it could break existing code. The jQuery folks have shown that they aren't necessarily afraid of "breaking" legacy code, but I suppose in this case, they decided it made sense to not risk introducing regressions. – rinogo Jun 01 '17 at 18:18
  • Looks like that's the case. `live()` was deprecated in 1.7 and removed in 1.9. http://api.jquery.com/live/ – rinogo Jun 01 '17 at 18:18
12

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:

$('button').live('click', doSomething);

function doSomething() {
    // do something
}

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:

$(document).on('click', 'button', doSomething);

function doSomething() {
    // do something
}

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.

ajbeaven
  • 8,509
  • 11
  • 74
  • 109
4

See the official Blog

[..]The new .on() and .off() APIs unify all the ways of attaching events to a document in jQuery — and they’re shorter to type![...]

FloydThreepwood
  • 1,579
  • 14
  • 24
2
.live()

This method is used to attach an event handler for all elements which match the current selector, now and in the future.

$( "#someid" ).live( "click", function() {
  console.log("live event.");
});

and

.on()

This method is used to attach an event handler function for one or more events to the selected elements below is the example.

$( "#someid" ).on( "click", function() {
  console.log("on event.");
});
Mohammed Abrar Ahmed
  • 1,775
  • 1
  • 11
  • 27
1

Good tutorial on difference between on vs live

Quote from the above link

What is wrong with .live()

Use of the .live() method is no longer recommended since later versions of jQuery offer better methods that do not have its drawbacks. In particular, the following issues arise with the use of .live():

  1. jQuery attempts to retrieve the elements specified by the selector before calling the .live() method, which may be time-consuming on large documents.
  2. Chaining methods is not supported. For example, $(“a”).find(“.offsite, .external”).live( … ); is not valid and does not work as expected.
  3. Since all .live() events are attached at the document element, events take the longest and slowest possible path before they are handled.
  4. Calling event.stopPropagation() in the event handler is ineffective in stopping event handlers attached lower in the document; the event has already propagated to document.
  5. The .live() method interacts with other event methods in ways that can be surprising, e.g., $(document).unbind(“click”) removes all click handlers attached by any call to .live()!
venkat
  • 2,240
  • 1
  • 14
  • 13
0

I am the author of a Chrome extension "Comment Save" which uses jQuery, and one which used .live(). The way the extension works is by attaching a listener to all the textareas using .live() - this worked well since whenever the document changed it would still attach the listener to all the new textareas.

I moved to .on() but it doesn't work as well. It doesn't attach the listener whenever the document changes - so I have reverted back to using .live(). That is a bug I guess in .on(). Just be careful about it I guess.

Mauro Rocco
  • 4,700
  • 1
  • 23
  • 39
PixelPerfect3
  • 100
  • 1
  • 1
  • 6
  • 10
    You must be using it wrong - it does have slightly different syntax to the `.live()` method. The equivalent `.on()` for `$('p').live('click', function () { alert('clicked'); });` is `$(document).on('click', 'p', function () { alert('clicked'); });`. Note that you use the `.on()` method on the `document` and then specify the element you want to attach the event handler to listen to in its second parameter. – ajbeaven Jan 04 '13 at 04:12
  • 1
    You can read more on this here: http://api.jquery.com/on/. Look under the heading **Direct and delegated events** – ajbeaven Jan 04 '13 at 04:14
  • You are right - I actually realized I was not writing it correctly right after I wrote the answer. It only works partially if you use it the same way as live(). If you write it the correct way on() works, but still not as well as live() in my experience. I'm going to test it more since on's performance seems much better. – PixelPerfect3 Jan 07 '13 at 07:16
  • 1
    I'd suggest having a read of this article too: http://www.elijahmanor.com/2012/02/differences-between-jquery-bind-vs-live.html – ajbeaven Jan 07 '13 at 18:57
  • @ajbeaven you are right. We cannot use .on() as $('selector').on('event',function) to get the effect of .live(). For this we have to use $(document).on('event','selector',function). – Ramsharan May 05 '13 at 12:37
  • 1
    We can also do $(selector1).on(event,selector2,function) where selector1 is parent and selector2 is child of selector1. This minimizes the search area as you donot have to search whole document. – Ramsharan May 05 '13 at 12:59
  • And according to http://www.elijahmanor.com/2012/02/differences-between-jquery-bind-vs-live.html, we can use .on() in three different ways. It can be used as .bind(), .live(), and .delegate() and it has different behaviours according to how we use it. – Ramsharan May 05 '13 at 13:23
  • 1
    @ajbeaven you should turn your first comment here into an answer (that is what I was looking for when I arrived here). – atwright147 Sep 17 '13 at 14:56
  • @atwright147 Thanks, that's a good idea. I've added a new answer. – ajbeaven Sep 17 '13 at 20:56
0

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..

var tabs = $('#tabs').tabs();
                                        // live() methos attaches an event handler for all
                                        //elements which matches the curren selector
        $( "#tabs span.ui-icon-close" ).live( "click", function() {


            // fetches the panelId attribute aria-control which is like tab1 or vice versa
            var panelId = $( this  ).closest( "li" ).remove().attr( "aria-controls" );
            $( "#" + panelId ).remove();
            tabs.tabs( "refresh" );
        });

and it works preety much cool...

Hiren
  • 57
  • 1
  • 10
  • Welcome to SO. Pleasy try to elaborate on your answers and don't just provide links, link-only answers are regarded bad practice here. – mata Jun 27 '14 at 06:58
  • Thanks.. I will keep this in my mind for the future answer.. :) – Hiren Jun 27 '14 at 07:12
-1

I have a requirement to identify browser closed event. After Doing to of research I am doing following using jQuery 1.8.3

  1. Turn ON a flag using following jQuery when hyperlink is clicked

    $('a').live('click', function() {cleanSession = false;});

  2. 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;});

  1. Turn ON a flag using following jQuery when any time form submit happens

$('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

N.S.
  • 239
  • 3
  • 9
  • 1
    This is not true, you must be using `.on` incorrectly or something else in your code is causing this to happen. Perhaps paste your code for your `.on` method. – ajbeaven Mar 25 '14 at 19:14
  • Yeah. This is not true. .on() is improved version of .live(). So, paste your code here. So that we will have some clarity – RecklessSergio Jan 30 '15 at 13:08