jQuery 1.7: The death of live() and bind()

October 2nd, 2012
|

For what seems to be a good reason, jQuery 1.7 has deprecating the bind() and live() functions.  You can read about this at the jQuery API website (http://api.jquery.com/live/).  Instead, it is being replaced with the all encapsulating on() function.  This function can be used instead of most of the event functions.  If we want to add a click event to an element, we usually do something like this:

$('.element').click(function(){
    // Our other code
});

Well it may be a surprise to some of you that this is just a shortcut function for bind().  The following does exactly the same thing as click().

$('.element').bind('click', function() {
    // Our other code
});

In the same way, if you are creating elements on the fly or are fading in hidden elements and those elements need a click event, you could always have called live() on them.

$('.newElement').live('click', function(){
    // Our other code
});

However, now both bind() and live() are being replaced by the all encapsulating on() function.  To call what used to be a bind() with on(), do it like this:

$('.newElement').on('click', function(){
    // Our other code
});

This is pretty similar to bind() so it is not very interesting.  But live() on the other hand is.  It is more literal to what is happening in the document, and that is why I like it.  What happens is, you actually add the event to the document and then on the event, jQuery checks your selectors and passes the event down to them.  It can be done like so:

$(document).on('click', '.newElement', function(){
    // Our other code
});

Keep in mind that $(this) is still our .element jQuery object.  Interesting, but a little confusing and so I thought I’d post on it.

Comments are closed.

Comments have been closed for this post. If you would like to ask a question or need help, please post in the forums.