I have HTML like this
<details draggable="true" open="">
<summary>author</summary>
<div draggable="true">name</div>
<div draggable="true">company</div>
</details>
I want seperate "dragstart" event listeners for the divs and a third for the containing block when i start my cursor on summary.
Currently div.addEventListener("dragstart", (event) => {})
also fires the event for the parent when the child divs are dragged. I did try event.stopPropagation
but that makes the drop stop working when i drop onto a rich text field (the dataTransfer data doesn’t transfer).
2
Answers
You can try this approach:
Create a variable (global for listener functions) where you will track which event is called
When started child
dragstart
then set this variable totrue
When started child
dragend
then set this variable tofalse
Here is complete code for basic situation:
It sounds like you have two event listeners. You can just use one event listener, listening on a parent element (Event delegation). The
e.target
will always be either the<details>
or the<div>
.In this example I add a class name to the element being dragged. That way I know what the element in in the
drop
event callback function. And then depending on thenodeName
you can decide what to do next. In the example I clone either the<details>
or the<div>
and append it on an appropriate element.