Drag and drop is a common feature in modern interfaces that allows users to reorder elements in an intuitive and direct way. Thanks to HTML5 APIs, this functionality can be implemented without relying on external libraries, giving full control over the behavior.
Basic HTML Structure
To enable reordering, you need a container with multiple child elements, each marked as "draggable". A generic markup example could be:
<ul class="sortable-list">
<li class="sortable-item" draggable="true">Item 1</li>
<li class="sortable-item" draggable="true">Item 2</li>
<li class="sortable-item" draggable="true">Item 3</li>
</ul>
Handling Drag and Drop Events
The mechanism relies on listening to events like dragstart
, dragover
, and drop
. The dragged element is stored and then inserted into the new position depending on where it is released.
document.addEventListener('DOMContentLoaded', () => {
const containers = document.querySelectorAll('.sortable-list');
containers.forEach(container => {
let draggedElement = null;
container.addEventListener('dragstart', e => {
if (e.target.classList.contains('sortable-item')) {
draggedElement = e.target;
e.dataTransfer.effectAllowed = 'move';
e.target.classList.add('dragging');
}
});
container.addEventListener('dragend', () => {
if (draggedElement) {
draggedElement.classList.remove('dragging');
draggedElement = null;
}
});
container.addEventListener('dragover', e => {
e.preventDefault();
const target = e.target.closest('.sortable-item');
if (target && target !== draggedElement) {
const rect = target.getBoundingClientRect();
const offset = e.clientY - rect.top;
const shouldInsertAfter = offset > rect.height / 2;
container.insertBefore(
draggedElement,
shouldInsertAfter ? target.nextSibling : target
);
}
});
});
});
Accessibility Considerations
The basic implementation of drag and drop is visual, but to improve accessibility it is recommended to also offer alternative reordering methods, such as keyboard commands or dedicated buttons.
Conclusion
Using the native drag and drop APIs makes it possible to implement a system for reordering elements on a page in just a few lines of code. This approach is flexible, requires no external dependencies, and can be easily extended to integrate automatic server-side saving or advanced features.