| 1 |
<style> |
| 2 |
div { |
| 3 |
position: relative; |
| 4 |
user-select: none; |
| 5 |
} |
| 6 |
#from { |
| 7 |
cursor: pointer; |
| 8 |
} |
| 9 |
</style> |
| 10 |
<body> |
| 11 |
<div id="container"> |
| 12 |
<div id="to"> |
| 13 |
Drop here |
| 14 |
</div> |
| 15 |
<div id="from"> |
| 16 |
Drag me |
| 17 |
</div> |
| 18 |
</div> |
| 19 |
</body> |
| 20 |
<script> |
| 21 |
const from = document.querySelector('#from'); |
| 22 |
const to = document.querySelector('#to'); |
| 23 |
|
| 24 |
let start = null; |
| 25 |
from.addEventListener('mousedown', e => { |
| 26 |
start = { x: e.clientX, y: e.clientY }; |
| 27 |
}); |
| 28 |
|
| 29 |
document.body.addEventListener('mousemove', e => { |
| 30 |
if (start) { |
| 31 |
from.style.top = (e.clientY - start.y) + 'px'; |
| 32 |
from.style.left = (e.clientX - start.x) + 'px'; |
| 33 |
} |
| 34 |
}); |
| 35 |
|
| 36 |
document.body.addEventListener('mouseup', e => { |
| 37 |
const box = to.getBoundingClientRect(); |
| 38 |
if (start && box.left < e.clientX && box.right > e.clientX && box.top < e.clientY && box.bottom > e.clientY) |
| 39 |
to.textContent = 'Dropped'; |
| 40 |
start = null; |
| 41 |
from.style.top = '0'; |
| 42 |
from.style.left = '0'; |
| 43 |
}); |
| 44 |
</script> |