How to prevent parent’s onclick event from firing when a child tag is clicked with jquery?

Generally, Javascript events bubble (listen) to the highest point in the DOM to which a click event had been attached. So even if you don’t have any other explicitly click-able 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.

For example, i have:


Solution

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 tells them to stop event bubbling after their own handler executes:

$("#clickable a").click(function(e) {
   e.stopPropagation();
})
Share

Possibly Related posts:

Tags : , ,

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

One Comment

Leave Comment

Freelance Jobs