DEV Community

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

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

1

#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.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more