JSFiddle - React, Tailwind, and code Playground
by gilly3
HTML
<div id="dragTarget"></div>
<div draggable="true"></div>
<div draggable="true"></div>
<div draggable="true"></div>
CSS
div {
position: absolute;
height: 50px;
width: 50px;
background-color: #eee;
border: 1px solid #ccc;
top: 5px;
left: 5px;
}
#dragTarget {
top: 60px;
height: 180px;
width: 170px;
background-color: #000;
border-color: #000;
}
div:nth-child(2) { left: 5px; }
div:nth-child(3) { left: 65px; }
div:nth-child(4) { left: 125px; }
.overlap { background-color: #ff0; }
JavaScript
onload = function() {
var a = document.getElementById("dragTarget");
a.ondragenter = dragEnter;
a.ondragleave = dragLeave;
[].slice.call(document.querySelectorAll("[draggable=true]")).forEach(function(el){
el.ondragstart = dragStart;
el.ondrag = drag;
el.ondragend = dragEnd;
});
};
var dragging = [];
function dragEnter(e) {
dragging.forEach(function(el) {
if (el.draggingAt.x == e.x && el.draggingAt.y == e.y) {
el.className += " overlap";
}
}, this);
}
function dragLeave(e) {
dragging.forEach(function(el) {
if (el.draggingAt.x == e.x && el.draggingAt.y == e.y) {
el.className = el.className.replace(/ overlap\b/g, "");
}
}, this);
}
function drag(e) {
this.draggingAt = { x: e.x, y: e.y };
}
function dragStart(e) {
e.dataTransfer.setData('text/html', '');
dragging.push(this);
}
function dragEnd(e) {
dragging.splice(dragging.indexOf(this), 1);
}