How do I prevent a parent's onclick event from firing when a child anchor is clicked?

I’m currently using jQuery to make a div clickable and in this div I also have anchors. The problem I’m running into is that when I click on an anchor both click events are firing (for the div and the anchor). How do I prevent the div’s onclick event from firing when an anchor is clicked?

Here’s the broken code:

JavaScript

var url = $("#clickable a").attr("href");

$("#clickable").click(function() {
    window.location = url;
    return true;
})

HTML

<div id="clickable">
    <!-- Other content. -->
    <a href="http://foo.com">I don't want #clickable to handle this click event.</a>
</div>

88 thoughts on “How do I prevent a parent's onclick event from firing when a child anchor is clicked?”

  1. 106339 276795Good post. I be taught 1 thing far more challenging on completely different blogs everyday. It will all the time be stimulating to learn content from other writers and apply slightly one thing from their store. Id desire to use some with the content material on my weblog whether you dont mind. Natually Ill give you a hyperlink on your net weblog. Thanks for sharing. 903431

    Reply

Leave a Comment