简体   繁体   中英

Stop click from propagating to a parent

When a particular element is clicked, I want to call a function. When any of its children are clicked, I do not want to call the function.

I am not using jQuery.

Example:

I created a modal:

<div class="fullscreen-overlay">
  <div class="card">
    ...
  </div>
</div>

I want to call my closeModal() function when ".fullscreen-overlay" is clicked, but not when ".card" or any of its content are clicked.

jsfiddle:

https://jsfiddle.net/5kuwmf9s/

Research:

I could've sworn there was a CSS attribute for this, but after Googling and searching on SO for it, I can't find it / might've been imagining it. "pointer-events" stops it on the target element, not bubbling.

Theres another answer that suggests attaching an event handler to ALL children that catches their events and stops propagation - which seems unnecessary. My children are dynamic, and this will get complicated to keep attaching handlers.

You might have compared event's target and currentTarget

They would be equal only if the current element is the one that was the initial source of the event:

function handleClick(e){
  if (e.target === e.currentTarget) {
    alert('clicked!');
  }
}

References:

JSFiddle: https://jsfiddle.net/u78k4k6t/

  • try use an element and style it as your '.fullscreen-overlay' and bind event to this element
  • as the answer link shows
  • use event.target or event.srcElement

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