JSFiddle - React, Tailwind, and code Playground
by Ben Clayton
HTML
<div class="container">
<div class="box" draggable=true>
A
</div>
<div class="box" draggable=true>
B
</div>
<div class="box" draggable=true>
C
</div>
</div>
CSS
.container {
padding: 30px;
position: fixed;
width:calc(100% - 4px);
height:calc(100% - 4px);
border: 1px solid red;
margin: 2px;
}
.box {
display:inline-block;
padding:10px;
width:100px;
border: 1px solid gray;
border-radius: 5px;
}
JavaScript
document.addEventListener('DOMContentLoaded', (event) => {
var dragSrcEl = null;
function handleDragStart(e) {
this.style.opacity = '0.4';
dragSrcEl = this;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', this.innerHTML);
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault();
}
e.dataTransfer.dropEffect = 'move';
return false;
}
function handleDragEnter(e) {
this.classList.add('over');
}
function handleDragLeave(e) {
this.classList.remove('over');
}
function handleDrop(e) {
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
if (dragSrcEl != this) {
dragSrcEl.innerHTML = this.innerHTML;
this.innerHTML = e.dataTransfer.getData('text/html');
}
return false;
}
function handleDragEnd(e) {
this.style.opacity = '1';
items.forEach(function (item) {
item.classList.remove('over');
});
}
let items = document.querySelectorAll('.container .box');
items.forEach(function(item) {
item.addEventListener('dragstart', handleDragStart, false);
item.addEventListener('dragenter', handleDragEnter, false);
item.addEventListener('dragover', handleDragOver, false);
item.addEventListener('dragleave', handleDragLeave, false);
item.addEventListener('drop', handleDrop, false);
item.addEventListener('dragend', handleDragEnd, false);
});
});