JSFiddle - React, Tailwind, and code Playground
by Boba Poshtar
HTML
<section>
<div></div>
<span>test</span>
</section>
CSS
section {
padding: 30px; border: 1px solid navy;
}
div { margin-bottom: 16px; width: 200px; height: 120px; border: 1px solid red; }
span { display: inline-block; padding: 2px 10px; border: 1px solid green; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; cursor: move; }
.over { background: pink; }
.move { opacity: 0.5; boxShadow: 0 0 3px rgba(0, 0, 0, 1);
position: absolute; }
.movable { cursor: move; }
JavaScript
var span = document.querySelector('span');
var div = document.querySelector('div');
span.onmousedown = function(e){
document.body.appendChild(this);
this.classList.add('move');
span.style.left = e.pageX + 'px';
span.style.top = e.pageY + 'px';
}
window.onmousemove = function(e){
if (!span.classList.contains('move')) { return false; }
span.style.left = e.pageX + 'px';
span.style.top = e.pageY + 'px';
div.classList[overDiv(e.pageX, e.pageY) ? 'add' : 'remove']('over');
}
window.onmouseup = function(e){
if (!span.classList.contains('move')) { return false; }
div.classList.remove('over');
span.classList.remove('move');
if (overDiv(e.pageX, e.pageY)) {
div.appendChild(span);
}
}
function overDiv(x, y){
var d = {
x: div.offsetLeft,
y: div.offsetTop,
w: div.offsetLeft + div.offsetWidth,
h: div.offsetTop + div.offsetHeight
};
return x > d.x && x < d.w && y > d.y && y < d.h;
}