WikiGalaxy

Personalize

HTML5 Drag and Drop API

Overview

HTML5 introduces a native API for performing drag and drop interactions. These interactions are more intuitive as users can directly interact with elements on the web page.

Basic Structure

Drop here

Example Explanation:

The `draggable="true"` attribute is used to make an element draggable. The drag event starts when the user begins to drag the element.

Key Drag and Drop Events

Drag Events:

The following events are essential for implementing drag and drop functionality:

  • dragstart: Fires when the user starts dragging an element.
  • dragenter: Fires when the dragged element enters a drop target.
  • dragover: Fires when the dragged element is held over a drop target.
  • drop: Fires when the dragged element is dropped on the drop target.

Example Code with Events

Drag me!
Drop here
function allowDrop(event) { event.preventDefault(); } function drag(event) { event.dataTransfer.setData("text", event.target.id); } function drop(event) { event.preventDefault(); var data = event.dataTransfer.getData("text"); event.target.appendChild(document.getElementById(data)); }

Detailed Explanation:

In this example, `allowDrop(event)` is necessary to prevent the default handling of the element, enabling the `drop` event. The drag event sets the data type and the value (ID of the element), and the drop event appends the dragged element to the drop target.

Practical Use Case

Use Cases:

Drag and drop can be used in various real-world scenarios such as:

  • File uploading: Allow users to drag and drop files for upload.
  • Task management: Rearrange tasks or items in a list.
  • Interactive UI: Enhance user experience with interactive interfaces.
logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025