简体   繁体   中英

Prevent underlying div onclick event to trigger

I'm trying to create an overlay which has an outer div (half see-through) and above an smaller inner content div. Clicking on the outer area makes the overlay dissappear. Clicking on the content area should interact with the overlay content.

Looking at my example code, clicking on the red area first raises an alert "red" and afterwards an alert "black" thus closing the overlay immediatly after the first interaction.

How can I prevent the onclick event of the underlying black div to trigger when the above red div is clicked?

  <div onclick = "window.alert('black')" style = "background-color:black; width:100%; height:100%"> <div onclick = "window.alert('red')" style = "background-color:red; position: absolute; top:10%; left:10%; width: 80%; height: 80%;"> some content </div> </div> 

I couldn't find anything online about that except people setting pointer-events to none which would disable the user to interact with the overlay content. Also setting different z-indeices didn't work either.

If you want to verify the clickthrough happening: https://onlinegdb.com/rJbOmB0FV

This is more of a javascript behaviour you're experiencing.

Bubbling

The bubbling principle is simple.

When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.

Use event.stopPropagation()

Definition and Usage

  • The stopPropagation() method prevents propagation of the same event from being called.

  • Propagation means bubbling up to parent elements or capturing down to child elements.

https://www.w3schools.com/jsref/event_stoppropagation.asp

Update

A simple function will be easier to handle.

Something like this:

 const alert = (text) => { event.stopPropagation(); window.alert(text) } 
 <div onclick = "alert('black')" style = "background-color:black; width:100%; height:100%"> <div onclick = "alert('red')" style = "background-color:red; position: absolute; top:10%; left:10%; width: 80%; height: 80%;"> some content </div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM