Source Code:
(back to article)
Submit
Result:
Report an issue
<!DOCTYPE html> <html lang="en"> <head> <title>Draggable Element Example</title> <style> #draggable { width: 100px; height: 100px; background-color: red; position: absolute; cursor: pointer; } </style> </head> <body> <div id="draggable"></div> <script> const elem = document.getElementById('draggable'); elem.onmousedown = function(event) { let shiftX = event.clientX - elem.getBoundingClientRect().left; let shiftY = event.clientY - elem.getBoundingClientRect().top; function moveAt(pageX, pageY) { elem.style.left = pageX - shiftX + 'px'; elem.style.top = pageY - shiftY + 'px'; } function onMouseMove(event) { moveAt(event.pageX, event.pageY); } document.addEventListener('mousemove', onMouseMove); elem.onmouseup = function() { document.removeEventListener('mousemove', onMouseMove); elem.onmouseup = null; }; }; elem.ondragstart = function() { return false; }; </script> </body> </html>