Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery 'on' vs. 'live'

Tags:

jquery

I have a scenario where JQuery 'on' & 'live' do not perform the same. Perhaps someone can point out why. I am using JQuery 1.7.2 with my project and in this build, 'live' has been replaced with 'on'. I am using the following code in a listing page. Basically, this page has an alphabetical bar that the user can click & will load all the clients with that last name. I would like the link to execute via ajax.

Code:

$("a.listajax").on("click", function (e) {
    e.preventDefault();
    var url = $(this).attr("href");
    $("div.content").load(url + " div.content");
    return false;
});

The problem here is that when I first load the page and click on a link, everything works fine. The page gets loaded via ajax. However, after that all the links lose their bindings & then if I click on any links, I get an entire page loads.

I replaced the 'on' with 'live' and the links started behaving perfectly, even on subsequent clicks.

What am I missing?

like image 538
Skadoosh Avatar asked Feb 21 '23 04:02

Skadoosh


2 Answers

One does not simply replace .live with .on.

$("a.listajax").live('click', function(e))

Is equivalent to:

$(document).on('click', 'a.listajax', function(e))

Important

If there's a common ancestor for all your .listajax anchors that will not be removed from the DOM, you should use that (the deepest one possible) instead of document; this will improve performance.

like image 51
Ja͢ck Avatar answered Feb 22 '23 18:02

Ja͢ck


That's the whole point of live(). It rebinds new DOM elements when they are created. There are a lot of similar questions on jQuery's site, like this one, because it can be a bit confusing.

According to the jQuery docs, you use live() to:

Attach an event handler for all elements which match the current selector, now and in the future.

The "...in the future" part is key, because on() does not have that.

like image 34
woz Avatar answered Feb 22 '23 18:02

woz