views:

207

answers:

2

Here's the problem I'm having. I have two jQuery .live() events, both for click events. These are initialized at the beginning of the page's load; they then wait until items matching the selector come along and are clicked on. Now, the problem with these is that when an item is added to the DOM that matches the selector, the live events are unbound (or maybe not - they just don't work at all. I've verified that they aren't even being called, too (set a breakpoint inside of the function in Firebug, and when I clicked a link matching the selector, it never fired - thus the function isn't even being called).

Moreover, it isn't only live events that match these particular selectors that get screwed up - it's EVERY live event that is unbound (or whatever else is happening) when the new items are added.

Has anybody ever had any experiences like this with the live events in jQuery? ... Or found a solution?

A: 

Sample code might help diagnose the issue =) Are you certain that the element in question matches the selector you've given? Because late additions to the DOM are precisely the problem that live was built to solve.

DDaviesBrackett
Yeah, I understand that. I wish I could give code samples, but a lot of it is proprietary work for my company, lol. Let me see if I can rustle up something similar so as not to give away information about what we're doing...
John Nicely
+1  A: 

One possibility is that your matched elements are contained by an element that handles the click event and stops propagation of the click event.

For example:

<script type="text/javascript">
    $(function() {
        $(".selector").live("click", function() { alert("clicked"); });
    });
</script>
<div onclick="event.stopPropagation();">
    <div class="selector">Click me</div>
</div>

In this example, clicking on "Click me" will not execute the event assigned by the .live method. This is because .live binds the event at a higher level of the DOM (see Josh Powell's comment here) and so, due to the nature of event bubbling, "event.stopPropagation();" gets executed before your live event. And since it stops propagation, your live click event never executes.

An alternatve is to use the livequery plugin for jquery which binds on each matched element. (I tried to provide a link, but as a new user, stackoverflow prevented me from posting more than one link)

Joel Harris