EN ES
Home > Web development > Javascript Tutorials > How to Implement Drag and Drop in JavaScript with Practical Examples

How to Implement Drag and Drop in JavaScript with Practical Examples

Diego Cortés
Diego Cortés
September 19, 2024
How to Implement Drag and Drop in JavaScript with Practical Examples

Drag and drop is a feature that allows users to interact with elements on a webpage by moving an object from one place to another. In this article, you will learn how to implement this functionality in your JavaScript projects, using practical examples to facilitate understanding.

What is Drag and Drop?

Drag and drop is an interaction technique that enables the movement of elements in a user interface. Users can drag an item and drop it in a different location, which can be useful for organizing content, task lists, among other things. In the context of JavaScript, this technique is based on a set of events that are triggered during the dragging action.

Drag and Drop Events in JavaScript

To implement drag and drop, it is necessary to understand the following events:

1. dragstart

This event is triggered when the dragging of an element begins. This is where you can store information about the element being dragged.

2. drag

This event is fired during the movement of the element, but it is generally used infrequently.

3. dragend

This event is activated when the drag operation ends, whether the item is dropped or the action is canceled.

4. dragenter

This occurs when the mouse pointer enters an area where an element can be dropped.

5. dragover

This event is triggered when an element is dragged over a drop context. It is crucial to allow the drop.

6. dragleave

This occurs when the mouse pointer leaves the area of a drop context.

7. drop

The event is fired when the element is dropped in a valid drop context.

Basic Implementation of Drag and Drop

Next, you will create a basic implementation of the drag and drop functionality. To simplify, we will create a list where items can be reordered.

HTML Structure

First, let's define a simple HTML structure with a list of draggable items.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Drag and Drop in JavaScript</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <ul id="myList">
        <li draggable="true">Item 1</li>
        <li draggable="true">Item 2</li>
        <li draggable="true">Item 3</li>
        <li draggable="true">Item 4</li>
    </ul>
    <script src="script.js"></script>
</body>
</html>

CSS Styles

Next, add some basic styles to improve the visualization:

/* styles.css */
body {
    font-family: Arial, sans-serif;
}

ul {
    list-style-type: none;
    padding: 0;
}

li {
    padding: 10px;
    margin: 5px;
    background-color: #f0f0f0;
    border: 1px solid #ccc;
    cursor: move;
}

JavaScript Script

Now, let's implement the logic to handle the drag and drop events.

// script.js
const listItems = document.querySelectorAll('#myList li');
let draggedItem = null;

listItems.forEach(item => {
    item.addEventListener('dragstart', () => {
        draggedItem = item;
        setTimeout(() => item.style.display = 'none', 0); // Hide the dragged item
    });

    item.addEventListener('dragend', () => {
        setTimeout(() => {
            draggedItem = null; // Reset the dragged item
            item.style.display = 'block'; // Show the item again
        }, 0);
    });

    item.addEventListener('dragover', (event) => {
        event.preventDefault(); // Necessary to allow the drop
    });

    item.addEventListener('dragenter', () => {
        item.style.border = '2px dashed #000'; // Visual effect
    });

    item.addEventListener('dragleave', () => {
        item.style.border = 'none'; // Remove visual effect
    });

    item.addEventListener('drop', () => {
        item.style.border = 'none'; // Remove visual effect
        if (draggedItem) {
            // Insert the dragged item before the dropped element
            item.parentNode.insertBefore(draggedItem, item);
        }
    });
});

How the Code Works

  1. dragstart: The element being dragged is saved and temporarily hidden.
  2. dragend: The element is reset when the drag operation is completed.
  3. dragover: This event is crucial as it allows the element to be dropped.
  4. dragenter and dragleave: They are used to apply a visual style to elements that can receive the drop.
  5. drop: The dragged element is inserted in the new position.

Conclusion

Implementing drag and drop in JavaScript is an effective way to enhance user interaction in your web applications. Through the practical examples presented, you should now have a solid understanding of how this functionality works. Experiment with the code and customize it according to your needs.

Additional Resources

I hope this article has been helpful for you to understand how to work with drag and drop functionality in JavaScript. Feel free to leave your comments and questions!

Diego Cortés
Diego Cortés
Full Stack Developer, SEO Specialist with Expertise in Laravel & Vue.js and 3D Generalist

Categories

Page loaded in 47.61 ms