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();
})

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

  1. Hello, thank you for your comments,
    there’s another way to do the same thing, you can use the following line of code:

    e.preventDefault();

    this line of code stops the propagation of the click event,
    usually this is neccesary when you use controls that have the attribute runa=”server”.

Leave a Reply