Reputation: 752
I am experiencing some weird behavior in jQuery (v1.7):
I am trying to set an event listener to an element that actually gets replaced at some point via ajax.
$(document.getElementById('element')).live('click', function() {
// do something on click
});
while this works fine with other methods, the live method refuses to run. when replacing this with the native jQuery selector it works. Why?
$("#element").live('click', function() {
// do something on click
});
Upvotes: 1
Views: 585
Reputation: 5792
Because live
will attach the actual event to the document, which is called delegation.
Then when a click happens, jQuery checks if the element in the selector was the origin of the event and if it is, your function gets called.
While $("#element") can see if there is an element matching the selector, $(document.getElementById("element));
can not, because there is no selector, just an object, which is missing after you remove it.
Upvotes: 1
Reputation: 887777
.live()
filters all click events to see which ones match the selector that you created the jQuery object from.
It has nothing to do with the elements currently in the jQuery object.
Writing $(element).live()
will not do anything, since there is no selector.
Upvotes: 1
Reputation: 5770
document.getElementById is grabbing an element that currently exists. When you pass a string, "#id", with live, jQuery is looking for events in the future on document.body that originate from an element with an ID matching that string.
As a side note, look into .on() as .live() is not only computationally expensive, but deprecated.
Upvotes: 2
Reputation: 25455
The native JavaScript getElementById gives you the actual DOM object whereas the jquery selector gives you a jquery wrapper around object(s).
.live needs a jquery wrapper to work I think.
Also you should use .on or .delegate as .live has been deprecated as of 1.7
Upvotes: 0
Reputation: 324750
I'm fairly sure that in the first case you are passing a simple node to the jQuery constructor, which means that as soon as that node is gone the object won't refer to anything anymore and so live
cannot work.
On the other hand, by passing it the jQuery selector instead, live
can constantly look for the element with that ID even if it is removed, re-added or otherwise kicked around.
Upvotes: 1
Reputation: 126072
live
doesn't work this way. The event bubbles up to the document and then the target
of the event is examined to see if it matches the selector.
It's likely that the element you're listening for events on does not exist when you bind the event handler, so getElementById
returns nothing.
When you think about the semantics of live
it doesn't make sense to pass it a DOM element.
Upvotes: 3