<div id="dragMe" class="draggable">Drag me</div>
.draggable {/* Indicate the element draggable */cursor: move;/* It will be positioned absolutely */position: absolute;/* Doesn't allow to select the content inside */user-select: none;}
mousedown
on the element: Track the current position of mousemousemove
on document
: Calculate how far the mouse has been moved, and determine the position of elementmouseup
on document
: Remove the event handlers of document
// The current position of mouselet x = 0;let y = 0;// Query the elementconst ele = document.getElementById('dragMe');// Handle the mousedown event// that's triggered when user drags the elementconst mouseDownHandler = function (e) {// Get the current mouse positionx = e.clientX;y = e.clientY;// Attach the listeners to `document`document.addEventListener('mousemove', mouseMoveHandler);document.addEventListener('mouseup', mouseUpHandler);};const mouseMoveHandler = function (e) {// How far the mouse has been movedconst dx = e.clientX - x;const dy = e.clientY - y;// Set the position of elementele.style.top = `${ele.offsetTop + dy}px`;ele.style.left = `${ele.offsetLeft + dx}px`;// Reassign the position of mousex = e.clientX;y = e.clientY;};const mouseUpHandler = function () {// Remove the handlers of `mousemove` and `mouseup`document.removeEventListener('mousemove', mouseMoveHandler);document.removeEventListener('mouseup', mouseUpHandler);};ele.addEventListener('mousedown', mouseDownHandler);