DEV Community

Cover image for #LearnedToday: Drag&Drop API
Daniel Zotti
Daniel Zotti

Posted on • Updated on • Originally published at danielzotti.it

#LearnedToday: Drag&Drop API

πŸ‘€ I have never used drag&drop functionality with vanilla JavaScript.

In the enterprise applications I work on every day, I usually rely on frameworks such as Angular, React, or Vue that provide easier ways to handle it and, in addition, solve the classic problems that I would have to handle by hand.

πŸ’‘ That's why I wanted to give it a try, developing a very basic project in HTML and JS.

Here, briefly, is what I figured out:

  • In order to activate the dragging functionality on a element, it must be set the draggable attribute on it.
<div class="item" draggable="true">Drag me</div>
Enter fullscreen mode Exit fullscreen mode
  • If we need to add some actions (e.g. save element's data for future purpose) once the element is "grabbed", a listener to the dragStart event must be added to it.
<div 
  id="my-item"
  class="item"
  draggable="true" 
  ondragstart=handleDragStart(event)
>Drag me</div>

<script>
handleDragStart(e) {
  console.log('You are dragging ', e.target.id)
}
</script>
Enter fullscreen mode Exit fullscreen mode
  • If we want to drop the selected element somewhere, we need to create one or more drop zones in the HTML. In order to create them, we need to make the target element listen to dragOver and drop events.
<div 
  class="dropzone"
  ondrop="handleDrop(event)"
  ondragover="handleDragOver(event)"
>
  Drop the dragging element here!
</p>

<script>
handleDrop(e) {
  e.preventDefault(); // prevent default action (e.g. open as link for some elements)
  // CODE HERE (e.g. append element to the drop zone)
}
handleDragOver(e) {
  e.preventDefault(); // Required to allow Drop event
}
</script>
Enter fullscreen mode Exit fullscreen mode

That's pretty much it!

Demo

As usual, I created a stackblitz project where you can use drag&drop to switch placements in a podium and choose which is the best πŸ† framework/library among AngularπŸ₯‡, VueπŸ₯ˆ, and ReactπŸ₯‰! (Try to guess what my ranking is 😁)

And here is the link to the demo if you just want to play with it!

P.S. I did not use the dataTransfer property, but I will create a more "data-driven" demo to explain this function as well in the future.

Top comments (0)