ckingchris
ckingchris

Reputation: 609

Using javascript, how do you skip, or remove, e.stopPropagation() from certain class names in an element?

Using javascript, how do you skip, or remove, e.stopPropagation() from certain class names in an element. In this case, the .trigger class in the .dropdown?

<div class="dropdown">
    <a href="#" class="trigger edit">Edit</a>
    <a href="#" class="trigger delete">Delete</a>
    <div class="content">
        <p>Some Text</p>
    </div>
</div>

JS

document.querySelector(".dropdown").addEventListener("click", e => {
    e.stopPropagation();
})

Upvotes: 0

Views: 1429

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206669

  • Go for Event.target that will give you the exact clicked element (not necessarily the one that has the Event attached! (.dropdown) in your specific case)
  • Having that target element, traverse the DOM starting (and including) that element up the ancestors chain in search for Element.closest()
  • Use an if statement to see if that element is found:

document.querySelector(".dropdown").addEventListener("click", e => {
  const elClassTrigger = e.target.closest(".trigger");
  if ( elClassTrigger ) e.stopPropagation();
});
<div class="dropdown">
    <a href="#" class="trigger edit">Edit</a>
    <a href="#" class="trigger delete">Delete</a>
    <div class="content">
        <p>Some Text</p>
    </div>
</div>

Important:

as a side-note, Event.stopPropagation() should never be used. There's not a single valid argument in having to stop an Event from bubbling the DOM and therefore notifying other layers in your application that something happened. And it can just cause problems.

Just a small example:

Imagine a custom dropdown, and a custom modal window, both close if one clicks somewhere outside - in the Document. Say the modal is open, and you click outside (in the wish to close it) but your click lands on a dropdown element. Congratulations, the dropdown opened, but the modal did not close since the Event did not propagated to notify its listener. Even funnier would be seeing the dropdown suddenly hover over the modal given a higher z-index in CSS! You got the idea.

Upvotes: 1

Related Questions