I have a Drupal site using jQuery 1.3, so that unfortunately I cannot use the live function. I need to intercept a click/change event of a dynamically created item. How can I do that without using live? I cannot upgrade to jquery 1.4.
3 Answers
In jQuery 1.3 if you need events .live() didn't support then (change properly in IE, etc) your best bet is still the .livequery() plugin:
$(".mySelector").livequery(function() {
$(this).change(function() {
//do something
});
});
.livequery() works differently, it actively looks for new elements and binds to them, rather than how .live() is a passive event listener...so it is a bit more expensive...but that's what there was before .live() was abailable.
1 Comment
In the method where you invoke your dynamic content, use the unbind command on the class type you want to leverage an event off. Then rebind directly afterwards. This will rebind all old elements as well as wire up the newly created one.
$('.className').unbind('click', functionName).bind('click', functionName);
Comments
It's not difficult to implement your own "live()"-function. Just add an event-handler to a container element that contains all your dynamically created items. If the event is now triggered on any of those items, it bubbles up to your event handler. In this handler, you can use $(event.target).is(selector) to check if the event was targeted at one of your dynamically created items.