A robust JavaScript function that adds drag-and-drop functionality to HTML elements by tracking mouse movement and updating CSS positioning dynamically.
/*
* Function: makeDraggable
* Description: Enables smooth drag-and-drop functionality for a target HTML element.
*
* Key logic:
* 1. Captures the initial mouse coordinates on 'mousedown'.
* 2. Calculates the delta (change) in mouse position during 'mousemove'.
* 3. Updates the element's 'top' and 'left' CSS properties based on the delta.
* 4. Cleans up event listeners on 'mouseup' to prevent memory leaks or stuck movement.
*
* Note: The element MUST have 'position: absolute' or 'position: fixed' in its CSS to move.
*/
function makeDraggable(element) {
// pos1 and pos2 track the change in mouse position
// pos3 and pos4 track the previous mouse position
let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
// If the element contains a header or specific drag-handle class, use that for grabbing
// otherwise, the entire element is the handle.
const handle = element.querySelector('.drag-handle') || element;
// Initialize the mouse down event
handle.onmousedown = dragMouseDown;
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// Get the starting cursor position
pos3 = e.clientX;
pos4 = e.clientY;
// Attach global listeners for movement and release
// We attach to 'document' so the drag continues even if the mouse leaves the element boundary
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// Calculate the distance the cursor has moved since the last frame
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
// Update 'previous' position for the next frame calculation
pos3 = e.clientX;
pos4 = e.clientY;
// Update the element's style coordinates
// offsetTop/offsetLeft represent the current relative coordinates
element.style.top = (element.offsetTop - pos2) + 'px';
element.style.left = (element.offsetLeft - pos1) + 'px';
}
function closeDragElement() {
// Clear listeners when the mouse button is released
document.onmouseup = null;
document.onmousemove = null;
}
}
// Usage Example:
// const myBox = document.getElementById('myBox');
// makeDraggable(myBox);