Reputation:
I have the following code that is not inside of a document ready?
$('a[href^="content/"]').live('click', function(event)
{
event.preventDefault();
....
This code comes just above the end body tag.
If the body of my HTML contains address links with the matching href then will they get the click even attached even if they are not yet in the DOM when this code executes? I'm a bit confused about how .live works. I thought normally you would not use .live on an actual element but rather on the containing block which you were going to fill with elements in the future.
Upvotes: 1
Views: 43
Reputation: 700342
The syntax of the live
method is a bit confusing, and tricky to use. That's why it has been superseeded by the more flexible delegate
method, and lately also incorprated into the on
method.
Your code is equivalent to:
$(document).delegate('a[href^="content/"]', 'click', function(event) { ...
So, the event is really hooked up to the document element.
What you are describing with the containing block is not possible to do with the live
method. It always hooks up the event to the document element. You use the delegate
or on
methods to hook up the event to a containing element.
Upvotes: 0
Reputation: 318508
I thought normally you would not use .live on an actual element but rather on the containing block which you were going to fill with elements in the future.
This is what delegates do. However, live events are very similar - they simply use the document itself as the "containing block". This has the disadvantage of jQuery having to check all events of the given type that occur on the page. So you should always use a delegate if possible (and usually it is possible!)
However, since jQuery 1.7 the various event registration methods have been unified into .on()
which registers both regular events and delegates depending on the arguments. For live events you simply create a delegate on document
instead.
Here are some examples on the old/new ways to register the live/delegate events (I'll omit regular ones since they are just like with .bind()
but with the new function name .on()
):
// live events
$('.foo').live('click', function(e) {}); // old
$(document).on('click', '.foo', function(e) {}); // new
// delegates
$('#container').delegate('.foo', 'click', function(e) {}); // old
$('#container').on('click', '.foo', function(e) {}); // new
Upvotes: 3