Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent a click handler being triggered when a child element is clicked?

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

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

And I've added an event (onclick) in div father like this

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

My question is why the son inherits the father in the event.

I want when I click on the Father div implement the event, but when i click on the son does not implement anything because it does not have any event.

like image 384
Lion King Avatar asked Jun 01 '11 14:06

Lion King


1 Answers

You can pass the event as one of the arguments in the closeFather function, then check whether the event target is the father element. See this example

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

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

<div id="father" onclick="closeFather(event)">
<div id="son"></div>
</div>
like image 87
Connell Avatar answered Oct 12 '22 23:10

Connell