Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent onClick from firing if another element is on top

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?

like image 415
JakAttk123 Avatar asked Jan 28 '23 09:01

JakAttk123


1 Answers

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>
like image 102
Narendra Jadhav Avatar answered Jan 30 '23 23:01

Narendra Jadhav