I'm writing a draggable class in vanilla js from scratch (this is NOT related to jQuery draggable), and it's working great, only my listeners are triggering on children of the selected node. I've tried e.stopPropagation()
inside of the listeners but it doesn't seem to change the outcome.
Here's a snippet of code from the class:
setListeners() {
const targets = document.getElementsByClassName("-jsDraggable");
[...targets].forEach(elem => {
elem.addEventListener("mousemove", e => this.handleMouseMove(e));
elem.addEventListener("mousedown", e => this.handleMouseDown(e));
elem.addEventListener("mouseup", e => this.handleMouseUp(e));
});
}
... and for example:
<ul class="-jsDraggable">
<li>No drag</li>
<li>No drag</li>
<li class="-jsDraggable">Can drag this item</li>
<li>No drag</li>
</ul>
In this scenario I would want both the <ul class="-jsDraggable">...</ul>
to be affected and also the single <li class="-jsDraggable">...</li>
inside, where dragging from one of the other list items would simply drag the main <ul class="-jsDraggable">...</ul>
element.
However, no matter which child node I interact with, regardless of how far down in the DOM it is compared to the node with the class, it triggers the handlers.
Any help would be greatly appreciated!
EDIT: Another example to clarify:
<article class="-jsDraggable">
<header>
<h1>Heading</h1>
</header>
<main>
<p>...</p>
</main>
</article>
No matter where I drag in this <article>
element, it should drag the entire group of HTML as one (since the parent of it all has the class). Currently, however, it's acting more like this:
<article class="-jsDraggable">
<header class="-jsDraggable">
<h1 class="-jsDraggable">Heading</h1>
</header>
<main class="-jsDraggable">
<p class="-jsDraggable">...</p>
</main>
</article>
... and every single child is also moving when it should only be moving the parent container that has the class attached.
I solved it, it wasn't working because I was setting the current element as this.elem = e.target
instead of this.elem = e.currentTarget
. After this, e.stopPropagation()
in the mousedown worked as expected.
Thanks for exposing me to e.currentTarget
, I wasn't aware of it before reading the help in this thread.