How to prevent click handler from triggering when a child is clicked?

I have two div tags, the first div is the father, and the second div is the son. Inside this father

<div id="father"> <div id="son"> </div> </div> 

And I added an event (onclick) to the father div like this

 <div id="father" onclick="closeFather()"> <div id="son"> </div> </div> 

My question is why the son inherits the father in this case.

I want when I click on the div of the father to implement the event, but when I click on the son, he does not implement anything, because he has no event.

+4
source share
3 answers

You can pass the event as one of the arguments to the closeFather function, and then check if the event target is a father element. See this example.

 function closeFather(e) { if(e.target == document.getElementById('father')) { //do stuff } }; 

Then in HTML you just need to add the event argument to the javascript function.

 <div id="father" onclick="closeFather(event)"> <div id="son"></div> </div> 
+4
source

This is caused by a JavaScript tag called the bbbling event . By default, your events will bubble in the DOM.

When you click on a child element of a node, you automatically fire the click event for it parent node (s).

By default, when an element is clicked, bubbles occur from within : this means that the event of the child click() element will be triggered first, then the parent element, etc.

You can solve the problem by adding a secondary click handler to your child and telling the browser to stop bubbling in a cross-browser compatible way ( see live example ):

 <script language="javascript"> function parentHandler(e) { alert('parent clicked'); }; function childHandler(e) { if (!e) var e = window.event; e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); alert('child clicked'); }; </script> <div id="parent" onclick="parentHandler(event);"> Foo <div id="child" onclick="childHandler(event)"> Bar </div> </div> 
+6
source

This event is bubbling. The bulk of DOM Events. You could return false and prevent bubbling in your handler ( closeFather , but you must pass an event to it) if the event is called by son .

+2
source

All Articles