Drag and Drop API
Drag and drop can move data through a pointer gesture. It should enhance an interaction rather than be the only way to complete it, particularly for keyboard and touch users.
How it works
- Mark a source draggable and place data in dataTransfer during dragstart. A drop target normally cancels dragover’s default behaviour to accept a drop.
- Read and validate the dropped value before using it. Do not insert arbitrary dropped HTML as trusted page content.
- Provide a button, menu, or other simple alternative that performs the same action without dragging.
A practical example
<p id="session" draggable="true">Bike repair</p>
<button type="button" id="choose">Choose Bike repair</button>
<div id="selection" role="status">No session selected.</div>
<script>
const source = document.getElementById('session');
const target = document.getElementById('selection');
const choose = () => { target.textContent = 'Selected: Bike repair'; };
source.addEventListener('dragstart', e => e.dataTransfer.setData('text/plain', 'bikes'));
target.addEventListener('dragover', e => e.preventDefault());
target.addEventListener('drop', e => { e.preventDefault(); if (e.dataTransfer.getData('text/plain') === 'bikes') choose(); });
document.getElementById('choose').addEventListener('click', choose);
</script>
In a normal page, either the drop action or the ordinary button selects the same session. The status text reports the outcome.