DEV Community

Cover image for HTML5 Drag and Drop API 🌐
Himanay Khajuria
Himanay Khajuria

Posted on

2 1

HTML5 Drag and Drop API 🌐

π–£  HTML5 Drag and Drop API β†’ A Step-by-Step Guide

The HTML5 Drag and Drop API lets you move elements around a webpage using your mouse. This feature is super useful for creating interactive user experiences like file uploads, kanban boards and more! πŸ–±οΈπŸ’‘


πŸ€·πŸ»β€β™€οΈ What is Drag and Drop❓

Drag and Drop allows you to grab an element and move it somewhere else on the webpage. You can make any HTML element draggable using draggable="true".

πŸ”₯ Quick Summary

1️⃣ Make an item draggable β†’ draggable="true" πŸ—οΈ

2️⃣ Detect when dragging starts β†’ dragstart 🎬

3️⃣ Allow dropping β†’ dragover βœ…

4️⃣ Move the item β†’ drop 🎯


✨ Step 1: Make an Item Draggable

First, you need an element that can be dragged. Add the draggable="true" attribute to make it draggable.

πŸ’πŸ»β€β™€οΈ Example:

<p id="dragItem" draggable="true">Drag me!</p>
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Now, this paragraph can be dragged! πŸŽ‰


🎬 Step 2: Detect When Dragging Starts

When you start dragging, you need to store some data about the dragged element. This is done using the dragstart event.

πŸ’πŸ»β€β™€οΈ Example:

document.getElementById("dragItem").addEventListener("dragstart", function(event) {
    event.dataTransfer.setData("text", event.target.id); // Store the ID of the dragged item
});
Enter fullscreen mode Exit fullscreen mode

βœ… What happens here?

πŸ‘‰ When dragging starts, the element's ID is saved so we can use it later.


🚦 Step 3: Allow Dropping

By default, elements don't allow dropping. You must enable it using the dragover event.

πŸ’πŸ»β€β™€οΈ Example:

document.getElementById("dropArea").addEventListener("dragover", function(event) {
    event.preventDefault(); // This allows dropping
});
Enter fullscreen mode Exit fullscreen mode

βœ… Why is this needed?

πŸ‘‰ Without event.preventDefault(), the item cannot be dropped inside another element.


➡ 𖦏 Step 4: Handle the Drop

Once the item is dropped, you need to move it inside the drop area.

πŸ’πŸ»β€β™€οΈ Example:

document.getElementById("dropArea").addEventListener("drop", function(event) {
    event.preventDefault();
    let draggedItem = event.dataTransfer.getData("text"); // Get the ID of dragged item
    event.target.appendChild(document.getElementById(draggedItem)); // Move it to new place
});
Enter fullscreen mode Exit fullscreen mode

βœ… What happens here?

πŸ‘‰ Retrieves the ID of the dragged item and moves it inside the drop area.


πŸ› οΈ Step 5: Create a Drop Area

You need a container where the dragged item will be dropped.

πŸ’πŸ»β€β™€οΈ Example:

<div id="dropArea" style="width: 200px; height: 200px; border: 2px dashed black;">
    Drop Here
</div>
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Now, when you drag the item and drop it into this area, it will move inside!


πŸ† Complete Example πŸ‘‡

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Drag and Drop Example</title>
</head>
<body>

    <p id="dragItem" draggable="true">Drag me!</p>

    <div id="dropArea" style="width: 200px; height: 200px; border: 2px dashed black;">
        Drop Here
    </div>

    <script>
        // Step 2: Dragging starts
        document.getElementById("dragItem").addEventListener("dragstart", function(event) {
            event.dataTransfer.setData("text", event.target.id);
        });

        // Step 3: Allow dropping
        document.getElementById("dropArea").addEventListener("dragover", function(event) {
            event.preventDefault();
        });

        // Step 4: Handle the drop
        document.getElementById("dropArea").addEventListener("drop", function(event) {
            event.preventDefault();
            let draggedItem = event.dataTransfer.getData("text");
            event.target.appendChild(document.getElementById(draggedItem));
        });
    </script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

🧠 Understanding dataTransfer.setData()

The dataTransfer.setData(format, data) method is used to store data when dragging an item.

πŸ’πŸ»β€β™€οΈ Example:

event.dataTransfer.setData("text", event.target.id);
Enter fullscreen mode Exit fullscreen mode

βœ… Explanation:

  • "text" β†’ Data type (could be "text/plain", "text/html", etc.).
  • event.target.id β†’ Saves the ID of the dragged item to be used later.

πŸ›‘ Why preventDefault() is Important?

By default, dropping is not allowed. We use event.preventDefault(); to enable it.

πŸ’πŸ»β€β™€οΈ Example:

document.getElementById("dropArea").addEventListener("dragover", function(event) {
    event.preventDefault(); // Allows dropping
});
Enter fullscreen mode Exit fullscreen mode

⚑βœͺ Why do we need it?

  • In dragover β†’ Enables dropping.
  • In drop β†’ Prevents unwanted browser actions (like opening a file). πŸ‘‰ Without preventDefault(), the item won’t be droppable.

✦ Full Flow Recap

πŸ“Œ Drag starts β†’ setData saves the ID.

πŸ“Œ Drag over drop area β†’ preventDefault enables dropping.

πŸ“Œ Drop happens β†’ getData retrieves ID and moves item.


πŸ“’ Learn More & Connect with Me!

🀩 Want to see this in action?

Check out my Technical Presentation πŸŽ₯:

πŸ”— View Presentation

πŸ’Ό Let’s connect on LinkedIn! πŸ‘₯πŸ’¬

β™‘ Happy Coding! β™‘

Image of PulumiUP 2025

Explore What’s Next in DevOps, IaC, and Security

Join us for demos, and learn trends, best practices, and lessons learned in Platform Engineering & DevOps, Cloud and IaC, and Security.

Save Your Spot

Top comments (1)

Collapse
 
davidbremmen profile image
David Bremmen β€’

Great Artricle!

Jetbrains Survey

Take part in the Developer Ecosystem Survey!

Share your thoughts and get the chance to win a MacBook Pro, an iPhone 16 Pro, or other exciting prizes. Help shape the coding landscape and earn rewards for your contributions!

Take the survey

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay