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?
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 theclickevent on theaelements that are in thedivas of when your code runs; newaelements in thedivwill not be hooked up.In your case, you’re better off using
delegate(live example, withload):That hooks
clickon thedivinstead. When the click occurs, it bubbles from the link to thediv, where the click handler created by jQuery examines it to see if it was actually a click on anyaelement. If so, it stops the click.As of jQuery 1.7, the new recommended syntax is
oninstead: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:
onclick, notonlick(you’re missing thec)javascript:pseudo-protocol on event handler attributes, onlyhrefs. 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.)