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

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


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 e.g.    // if($(e.target).is("div")) {    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) {   // Do something   e.stopPropagation();});


Use stopPropagation method, see an example:

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

As said by jQuery Docs:

stopPropagation method prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

Keep in mind that it does not prevent others listeners to handle this event(ex. more than one click handler for a button), if it is not the desired effect, you must use stopImmediatePropagation instead.


Here my solution for everyone out there looking for a non-jQuery code (pure javascript)

document.getElementById("clickable").addEventListener("click", function( e ){    e = window.event || e;     if(this === e.target) {        // put your code here    }});

Your code wont be executed if clicked on parent's childs