Lets say I have parent -> child -> sub child
, and I want to add a click event listener to all three elements. I am trying to achieve this: when sub child
is clicked, I want to skip the child
listener but still want to execute the parent
listeners. Is there any way to achieve this?
function parentClick() {
alert('parent click');
}
function childClick() {
alert('childClick');
}
function subChildClick() {
alert('subChildClick');
}
.parent {
width: 200px;
height: 200px;
background-color: green;
color: white;
padding: 20px;
}
.child {
width: 150px;
height: 150px;
background-color: yellow;
color: red;
padding: 20px;
}
.sub-child {
width: 100px;
height: 100px;
background-color: red;
color: white;
padding: 20px;
}
<div class="parent" onClick="parentClick()">
parent
<div class="child" onClick="childClick()">
child
<div class="sub-child" onClick="subChildClick()">sub child</div>
</div>
</div>
thanks.
3
Answers
Add flag that will be checked in
childClick
:One way (without requiring inelegant flags) is to check in the child click handler if the target of the click is the sub child.
Using contains
This is a better solution than using
matches
since you don’t need to find a good selector that will only apply to.sub-child
.Using matches
The selectors in the matches methods in the switch-case doesn’t need to be this specific since you’re only listening on events in the parent.
This way you only have one event listener and the code is relatively understandable
You could also use onClick