Donny P Donny P - 3 months ago 8
Javascript Question

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.

Answer

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/

Comments