HTML Drag and Drop (DnD) API

HTML Tutorial

HTML Drag and Drop (DnD) API

The HTML Drag and Drop (DnD) API allows users to drag elements from one location and drop them into another. This is commonly used in file uploads, sorting lists, and interactive interfaces.

It works natively in browsers using JavaScript and does not require any plugins.


Key Concepts

  1. Draggable Element

    • Any HTML element can be made draggable using the attribute:

      draggable="true"
  2. Drag Events

    • dragstart → Fired when dragging starts

    • drag → Fired during dragging

    • dragend → Fired when dragging ends

  3. Drop Zone Events

    • dragover → Fired when a dragged element is over a drop zone

    • drop → Fired when the element is dropped

    • dragleave → Fired when the dragged element leaves a drop zone

  4. Data Transfer

    • Use event.dataTransfer to pass data between draggable and drop target.


Example: Simple Drag and Drop


 


Explanation

  • draggable="true" → Makes the element draggable.

  • dragstart → Stores the element’s ID in dataTransfer.

  • dragover → Must prevent default to allow dropping.

  • drop → Retrieves the dragged element and appends it to the drop zone.


Key Points

  • The Drag and Drop API is purely client-side, requiring HTML, CSS, and JavaScript.

  • It is interactive and widely used for file uploads, sorting lists, and UI customization.

  • Use dataTransfer to pass data or even files.

  • Works best with modern browsers.

You may also like...