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();
})
Possibly Related posts:
- How to position a pop up element on mouse position coordinates with jquery
Here is a simple yet useful trick to position a tooltip (a div element etc) near the mouse click or pointer position using jQuery. In... - A note on DOM elements’ changed scope when using thickbox with jQuery
A similar situation may arise (atleast for me it did) when you try to invoke jQuery’s “thickbox” in conjunction with a custom onclick firing. I... - How to tell if an element exists with jQuery
For the reference. In general javascript we can check for the existence of an element using the method below: if(document.getElementById('element_id')) { //element exists } else... - Fix to jQuery plugin does not work on ajax loaded content
I had been loading table records through ajax pagination using jquery. Some of the urls/links (View Details, Edit and Delete) in loaded content had been... - A possible reason for jQuery thickbox appearing twice on a click
I had an issue while using thickbox with jQuery today. The thickbox which i had been using to show ajax content opened twice. It appeared...
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.






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”.