Source Code:
(back to article)
Submit
Result:
Report an issue
<!DOCTYPE html> <html> <head> <title>Title of the Document</title> <style> #text { cursor: pointer; cursor: pointer; width: 40px; height: 40px; } </style> </head> <body> <p id='text'>Drag the text</p> <script> text.onmousedown = function(event) { let shiftX = event.clientX - text.getBoundingClientRect() .left; let shiftY = event.clientY - text.getBoundingClientRect() .top; text.style.position = 'absolute'; text.style.zIndex = 1000; document.body.append(text); moveAt(event.pageX, event.pageY); // move the text along the coordinates (pageX, pageY) // taking into account the initial shifts function moveAt(pageX, pageY) { text.style.left = pageX - shiftX + 'px'; text.style.top = pageY - shiftY + 'px'; } function onMouseMove(event) { moveAt(event.pageX, event.pageY); } // move the text to the mousemove document.addEventListener('mousemove', onMouseMove); // drop the text, remove unneeded handlers text.onmouseup = function() { document.removeEventListener('mousemove', onMouseMove); text.onmouseup = null; }; }; text.ondragstart = function() { return false; }; </script> </body> </html>