HTML Drag/Drop

The HTML Drag and Drop API lets you move elements within a web page interactively using the mouse. Users can drag items and drop them into targets, enabling customizable interfaces like rearranging lists or implementing drag-and-drop file uploads. This API is accessed via JavaScript event handlers.

Key Topics

Draggable Attribute

Set draggable="true" on an element to make it draggable, and use JavaScript events like ondragstart and ondrop to handle the process.

Drag/Drop Events

Key events: dragstart, dragover, drop. Use preventDefault() on dragover to allow dropping.

Drag/Drop Example

This example allows dragging a div into another area. A full code sample is provided below.

<style>
#dragme {
    width:50px; height:50px; background:red;
}
#dropzone {
    width:200px; height:200px; border:2px dashed #333;
}
</style>

<div id="dragme" draggable="true">Drag me</div>
<div id="dropzone">Drop here</div>

<script>
var dragme = document.getElementById('dragme');
var dropzone = document.getElementById('dropzone');

dragme.ondragstart = function(e) {
    e.dataTransfer.setData('text/plain', 'Dragged Element');
};

dropzone.ondragover = function(e) {
    e.preventDefault();
};

dropzone.ondrop = function(e) {
    e.preventDefault();
    dropzone.appendChild(dragme);
};
</script>

Explanation: The red box can be dragged into the drop zone. JavaScript events handle the dragstart, dragover, and drop actions.

Key Takeaways

  • Set draggable to true on elements to enable drag.
  • Handle dragstart, dragover, and drop events in JavaScript.
  • Use preventDefault() in dragover to allow dropping.
  • Drag/Drop creates intuitive, interactive UIs.
  • Test across browsers, as implementations can vary.