Question

I used .stopPropagataion() to stop the bubbling in <li class="article"> when clicking on the <a> tag.

$(document).ready(function(){
   $(".article a").click(function(e) {
        e.stopPropagation();
   });
});

With this HTML:

<li class="article" onlick="javascript:somefunction();">
   <div id="div_id">
      <a>Some link</a>
   </div>
</li>

Everything worked fine, but then I used $('#div_id').load("div_html.html") to load some content into the div dynamically. Now my .stopPropagation() doesn't stop the bubbling. Why isn't it working anymore?

Was it helpful?

Solution

The problem is that when you update the content of the div, you destroy all of the elements that were inside it (including any event handlers attached to them). Your code is hooking the click event on the a elements that are in the div as of when your code runs; new a elements in the div will not be hooked up.

In your case, you're better off using delegate (live example, with load):

$(document).ready(function(){
   $(".article div").delegate("a", "click", function(e) {
        e.stopPropagation();
   });
});

That hooks click on the div instead. When the click occurs, it bubbles from the link to the div, where the click handler created by jQuery examines it to see if it was actually a click on any a element. If so, it stops the click.

As of jQuery 1.7, the new recommended syntax is on instead:

$(document).ready(function(){
   $(".article div").on("click", "a", function(e) {
        e.stopPropagation();
   });
});

Note that the order of arguments is different from delegate, but other than that it does the same thing.


I'd recommend avoiding combining old-style DOM0 handlers (event handler attributes) with new-style DOM2 code (your handler attached with jQuery). In many browsers, the two mechanisms are somewhat separate and may not play as nicely together as you'd like.

Two other comments on this:

onlick="javascript:somefunction();"
  1. It's onclick, not onlick (you're missing the c)
  2. You don't use the javascript: pseudo-protocol on event handler attributes, only hrefs. Just remove that part. (Why doesn't it cause an error? Because purely by coincidence, it's valid JavaScript — you're defining a label you never use.)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top