I learned about drag-and-drop using the HTML5 draggable attribute in my 2021-01-18 livestream:
What I Learned
draggable
Set draggable to true
to make an element draggable:
<input draggable="true" />
dragstart
Use the dragstart
event attribute to set the drag data:
<input
draggable="true"
ondragstart="event.dataTransfer.setData('text', event.target.tagName);"
/>
Or add the event listener using JavaScript:
document
.querySelector('input')
.addEventListener('dragstart', function onDragStart(event) {
event.dataTransfer.setData('text', event.target.tagName);
});
dragover
Use the dragover
event attribute to prevent the default action:
<fieldset ondragover="event.preventDefault();"></fieldset>
Or add the event listener using JavaScript:
document
.querySelector('fieldset')
.addEventListener('dragover', function onDragOver(event) {
event.preventDefault();
});
drop
Use the drop
event attribute to prevent the default action:
<fieldset ondrop="onDrop(event);"></fieldset>
<script>
function onDrop(event) {
var tagName = event.dataTransfer.getData('text');
event.target.appendChild(document.querySelector(tagName));
event.preventDefault();
}
</script>
Or add the event listener using JavaScript:
document
.querySelector('fieldset')
.addEventListener('drop', function onDrop(event) {
var tagName = event.dataTransfer.getData('text');
event.target.appendChild(document.querySelector(tagName));
event.preventDefault();
});