Source Code:
(back to article)
Submit
Result:
Report an issue
<div> <div id="draggable" style="width: 100px; height: 100px; background: blue; position: absolute; color: white; padding: 10px"> Drag me! </div> </div> <script> const draggable = document.getElementById('draggable'); let active = false; let currentX; let currentY; let initialX; let initialY; draggable.addEventListener('mousedown', function(event) { active = true; initialX = event.clientX - draggable.offsetLeft; initialY = event.clientY - draggable.offsetTop; }); document.addEventListener('mouseup', function() { active = false; }); document.addEventListener('mousemove', function(event) { if (active) { event.preventDefault(); currentX = event.clientX - initialX; currentY = event.clientY - initialY; draggable.style.left = currentX + 'px'; draggable.style.top = currentY + 'px'; } }); </script>