With the following example:
HTML:
<div class="parent" onclick="alert('hello!')">
<div class="child"></div>
</div>
CSS:
.parent {
align-items: center;
background: blue;
display: flex;
justify-content: center;
}
.child {
background: pink;
height: 100px;
width: 200px;
}
I want the onclick
event to fire when the user clicks on the parent / blue section. But not when the user clicks on the child / pink section. Right now the event fires even when the pink is being clicked, which is of course obvious since the .child
is a child of the parent. Is there any way to get past this?
With the following example:
HTML:
<div class="parent" onclick="alert('hello!')">
<div class="child"></div>
</div>
CSS:
.parent {
align-items: center;
background: blue;
display: flex;
justify-content: center;
}
.child {
background: pink;
height: 100px;
width: 200px;
}
I want the onclick
event to fire when the user clicks on the parent / blue section. But not when the user clicks on the child / pink section. Right now the event fires even when the pink is being clicked, which is of course obvious since the .child
is a child of the parent. Is there any way to get past this?
- Possible duplicate of How can I stop an onclick event from firing for parent element when child is clicked? – evolutionxbox Commented Feb 3, 2017 at 10:58
2 Answers
Reset to default 16Use event.stopPropagation()
method to event bubbling up to the DOM tree.
.parent {
align-items: center;
background: blue;
display: flex;
justify-content: center;
}
.child {
background: pink;
height: 100px;
width: 200px;
}
<div class="parent" onclick="alert('hello!')">
<div class="child" onclick="event.stopPropagation()"></div>
</div>
You have to use .stopPropagation()
for that event.
.parent {
align-items: center;
background: blue;
display: flex;
justify-content: center;
}
.child {
background: pink;
height: 100px;
width: 200px;
}
<div class="parent" onclick="alert('I am parent')">
<div class="child" onclick="event.stopPropagation()"></div>
</div>