JAVASCRIPT

Make Any DOM Element Draggable

Implement basic drag-and-drop functionality for any HTML element using vanilla JavaScript, updating its position dynamically with mouse events.

function makeDraggable(element) {
    let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;

    element.style.position = 'absolute'; // Essential for positioning
    element.style.cursor = 'grab';

    // When the mouse is pressed down on the element
    element.onmousedown = dragMouseDown;

    function dragMouseDown(e) {
        e = e || window.event;
        e.preventDefault();
        // Get the mouse cursor position at startup:
        pos3 = e.clientX;
        pos4 = e.clientY;
        document.onmouseup = closeDragElement;
        // Call a function whenever the cursor moves:
        document.onmousemove = elementDrag;
        element.style.cursor = 'grabbing';
    }

    function elementDrag(e) {
        e = e || window.event;
        e.preventDefault();
        // Calculate the new cursor position:
        pos1 = pos3 - e.clientX;
        pos2 = pos4 - e.clientY;
        pos3 = e.clientX;
        pos4 = e.clientY;
        // Set the element's new position:
        element.style.top = (element.offsetTop - pos2) + 'px';
        element.style.left = (element.offsetLeft - pos1) + 'px';
    }

    function closeDragElement() {
        // Stop moving when mouse button is released:
        document.onmouseup = null;
        document.onmousemove = null;
        element.style.cursor = 'grab';
    }
}

// Usage example:
// const myDraggableDiv = document.getElementById('myDraggableDiv');
// makeDraggable(myDraggableDiv);
How it works: This snippet provides a `makeDraggable` function that turns any HTML element into a draggable component. It works by attaching `mousedown`, `mousemove`, and `mouseup` event listeners. When `mousedown` occurs, it records the initial mouse position. As the mouse moves (`mousemove`), it calculates the difference in position and updates the element's `top` and `left` CSS properties. `onmouseup` stops the dragging process. For this to work, the element's CSS `position` property must be set to 'absolute' or 'fixed', allowing `top` and `left` to control its placement on the page.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs