Jquery onclick penetrating parent element

How would I stop onclick for an inner element while also clicking on its parent element.

 <div id="1" onclick="alert('1')"> <div id="2" onclick="alert('2')"></div> </div> 

If the second div (id = "2") is visible on top of the first and it is pressed, you will receive both warnings 1 and 2.

How can I avoid this, so I get a warning only from what I (apparently) click, Without completely disabling any onclick function that the external div may have.

Example: http://jsfiddle.net/DPCx8/

+8
javascript jquery onclick parent-child
source share
3 answers
 var outer = document.getElementById('outer'); outer.onclick = function(event) { alert('outer'); event.stopPropagation(); }​​ var inner = document.getElementById('inner'); inner.onclick = function(event) { alert('inner'); event.stopPropagation(); } 

http://jsfiddle.net/DYykA/1/

+7
source share

You need to stop the propagation from the child, so the event will not return to its original state.

 $("#inner").on("click", function(e){ e.stopPropagation(); }); 
+6
source share

use event.stopPropogation(); to prevent event bubbles

+3
source share

All Articles