How does the drag & drop feature work & implement it in raw js?
Published: 2024-02-21 18:37:20

The drag and drop mechanism in web development involves a set of events and properties provided by the HTML Drag and Drop API. Here's an overview of how it works:

1. **Drag Start (`dragstart`) Event:**
   - This event is triggered when the user starts dragging an element that has the `draggable` attribute set to `true`.
   - During this event, you set the data that you want to transfer to the drop target using `e.dataTransfer.setData()`.

    ```javascript
    function dragStart(event) {
      event.dataTransfer.setData("text/plain", event.target.id);
    }
    ```

2. **Drag Enter (`dragenter`) and Drag Over (`dragover`) Events:**
   - These events are triggered when a draggable element enters a valid drop target.
   - To allow a drop to occur, you need to prevent the default behavior of these events using `event.preventDefault()`.

    ```javascript
    function dragEnter(event) {
      event.preventDefault();
      // Highlight the drop target or perform other visual feedback.
    }

    function dragOver(event) {
      event.preventDefault();
      // Ensure the drop target is a valid location for the dragged element.
    }
    ```

3. **Drag Leave (`dragleave`) Event:**
   - This event is triggered when the dragged element leaves a valid drop target.
   - It's an opportunity to remove any visual feedback applied during `dragenter` or `dragover`.

    ```javascript
    function dragLeave(event) {
      // Remove visual feedback.
    }
    ```

4. **Drop (`drop`) Event:**
   - This event is triggered when the user releases the mouse button to drop the element onto the target.
   - You can access the transferred data using `event.dataTransfer.getData()`.
   - Perform any necessary actions, such as appending the dragged element to the drop target.

    ```javascript
    function drop(event) {
      event.preventDefault();
      const draggedElementId = event.dataTransfer.getData("text/plain");
      const draggedElement = document.getElementById(draggedElementId);
      // Append the dragged element to the drop target.
      event.target.appendChild(draggedElement);
    }
    ```

5. **Drag End (`dragend`) Event:**
   - This event is triggered when the drag operation is completed (either dropped or canceled).
   - You can perform cleanup or additional actions during this event.

    ```javascript
    function dragEnd(event) {
      // Perform any cleanup or additional actions.
    }
    ```

Remember to set the `draggable` attribute to `true` on the elements you want to make draggable. Additionally, ensure that you handle the necessary events to provide visual feedback and control the drop behavior.

Implementing a drag and drop feature in raw JavaScript involves handling various events such as `dragstart`, `dragenter`, `dragover`, `dragleave`, `drop`, and `dragend`. Here's a basic example to get you started:

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    #dragElement {
      width: 100px;
      height: 100px;
      background-color: lightblue;
      margin: 10px;
      cursor: grab;
    }
    #dropZone {
      width: 200px;
      height: 200px;
      background-color: lightgreen;
      margin: 10px;
    }
  </style>
  <title>Drag and Drop Example</title>
</head>
<body>

  <div id="dragElement" draggable="true" ondragstart="dragStart(event)">Drag me</div>
  <div id="dropZone" ondragenter="dragEnter(event)" ondragover="dragOver(event)" ondragleave="dragLeave(event)" ondrop="drop(event)">Drop here</div>

  <script>
    function dragStart(e) {
      e.dataTransfer.setData("text/plain", e.target.id);
    }

    function dragEnter(e) {
      e.preventDefault();
      document.getElementById("dropZone").style.border = "2px dashed red";
    }

    function dragOver(e) {
      e.preventDefault();
    }

    function dragLeave() {
      document.getElementById("dropZone").style.border = "none";
    }

    function drop(e) {
      e.preventDefault();
      document.getElementById("dropZone").style.border = "none";
      const draggedElementId = e.dataTransfer.getData("text/plain");
      const draggedElement = document.getElementById(draggedElementId);
      const dropZone = document.getElementById("dropZone");
      dropZone.appendChild(draggedElement);
    }
  </script>
</body>
</html>
```

This example consists of a draggable element (`dragElement`) and a drop zone (`dropZone`). The JavaScript functions handle the necessary drag and drop events. You can customize the styles and behaviors according to your needs.