I have an app in which something happens when you click the background, however, I don't want it to activate if you click on something else that is on top of the background. For example:
function handleClick() {
alert("Hello!");
}
.container {
position: absolute;
height: 100%;
width: 100%;
background: red;
}
.button {
position: absolute;
height: 20%;
width: 20%;
background: green;
}
<div class="container" onClick="handleClick()">
<div class="button"></div>
</div>
In this example, how can I prevent the alert from displaying when the user clicks on the green box?
You need to use inside div onclick="event.stopPropagation()"
Stopping Bubbling
A bubbling event goes from the target element straight up. Normally it goes upwards till <html>
, and then to document
object, and some events even reach window
, calling all handlers on the path.
But any handler may decide that the event has been fully processed and stop the bubbling.
The method for it is event.stopPropagation()
.
DEMO
function handleClick() {
alert("Hello!");
}
.container {
position: absolute;
height: 100%;
width: 100%;
background: red;
}
.button {
position: absolute;
height: 20%;
width: 20%;
background: green;
}
<div class="container" onClick="handleClick()">
<div onclick="event.stopPropagation()" class="button"></div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With