views:

856

answers:

5

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"&gt;I don't want #clickable to handle this click event.</a>
</div>
+9  A: 

Use stopPropagation function, see an example:

$("#clickable a").click(function(e) {
   e.stopPropagation();
})
Cleiton
+1 this was the perfect answer I was looking for.
James
A: 
<a onclick="return false;" href="http://foo.com"&gt;I want to ignore my parent's onclick event.</a>
andres descalzo
This also prevents the link from navigating.
Rex M
Yes, or do not what is needed?. Or need to be nevegar?
andres descalzo
+5  A: 

Events bubble to the highest point in the DOM at which a click event has been attached. So in your example, even if you didn't have any other explicitly clickable elements in the div, every child element of the div would bubble their click event up the DOM to until the DIV's click event handler catches it.

There are two solutions to this is to check to see who actually originated the event. jQuery passes an eventargs object along with the event:

$("#clickable").click(function(e) {
    var senderElement = e.target;
    //check if sender is the DIV element
    window.location = url;
    return true;
});

You can also attach a click event handler to your links which tell them to stop event bubbling after their own handler executes:

$("#clickable a").click(function(e) {
   e.stopPropagation();
})
Rex M
Great answer. Nice to know there are options too.
Jonathon Watney
A: 

add a as follows:

<a href="http://foo.com" onclick="return false;">....</a>

or return false; from click handler for #clickable like:

  $("#clickable").click(function() {
        var url = $("#clickable a").attr("href");
        window.location = url;
        return false;
   });
TheVillageIdiot
+1  A: 

You need to stop the event from reaching (bubbling to) the parent (the div). See the part about bubbling here, and jQuery-specific API info here.

Matt Ball
Cool. Thanks for the info about event bubbling.
Jonathon Watney