Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery onclick penetrating to parent element

How would I stop onclick for an inner element from also clicking through to its parent element.

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

If the second div (id="2") is visibly on top of the first, and it is clicked, You will get both alerts 1 & 2.

How can I avoid this so I only get the alert from what I'm (visibly) clicking on, Without completely disabling any onclick function the outer div may possess.

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

like image 674
d-_-b Avatar asked May 11 '12 06:05

d-_-b


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/

like image 150
Nikolai Borisik Avatar answered Nov 13 '22 08:11

Nikolai Borisik


You need to stop the propagation at the child, so the event doesn't bubble up to the parent.

$("#inner").on("click", function(e){
  e.stopPropagation();
});
like image 28
Sampson Avatar answered Nov 13 '22 07:11

Sampson


use event.stopPropogation(); to prevent bubbling of event

like image 34
rt2800 Avatar answered Nov 13 '22 06:11

rt2800