Search code examples
jqueryevent-handlinglive

Event assignment vs .live()


Time ago, I used to use this solution:

$('<div class="ok" />')
.appendTo('body');

$('div.ok')
.live('click',function(){ alert(); })

Now I use this one:

$('<div class="ok" />')
.appendTo('body')
.click(function(){ alert(); })

How is performance difference? I believe the second solution is better because It doesn't require a live() . Is it always this way (also with many elements) or not? why?


Solution

  • How is performance difference?

    Well, when you used to use live. live always bound to the document and preventing events from bubbling up was impossible too as the event was triggered after it already bubbled all the way through.

    In that sense live() was not very performance friendly.

    Your second code sample binds to the object directly as it is created, making it perform better and more flexible when compared to live(). You can now event prevent the event from bubbling up and so on.

    Binding the event at creation to the element directly compared to using on(), specifying the closest static element to bind to has only a very small performance benefit.

    // Performs slightly better than on() but cannot be executed from anywhere unless the element is added at the same time.
    $('<div class="ok" />').appendTo('body').click(function(){ alert(); })
    

    The benefit is smaller though than the benefit of being able to bind your event handlers before the element is added in a common method for example.

    The below does the same as your second code sample but can be nicely executed within a common method and does not have to be part of adding the dynamic element.

    // Can be called in a common init method for example and still work.
    $(body).on('click', '.ok', function(){ alert();})
    

    on() has the great benefit that you can separate the adding of elements from the binding of events.