Skip to main content

Command Palette

Search for a command to run...

Drag and Drop a Division Using JavaScript

Published
2 min readView as Markdown
A

Aspiring DevOps Engineer • Sharing my knowledge via blogs

In this guide, we’ll create a simple drag-and-drop functionality using JavaScript. This example allows you to drag a <div> element around the screen with your mouse.

Step 1: Set Up the HTML

Create an index.html file with the following content:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Drag and Drop Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: #f0f0f0;
        }
        #draggable {
            width: 150px;
            height: 150px;
            background-color: #4CAF50;
            color: white;
            text-align: center;
            line-height: 150px; 
            border-radius: 10px;
            cursor: grab;
            position: absolute;
        }
    </style>
</head>
<body>
    <div id="draggable">Drag me!</div>
<script src="app.js"></script>
</body>
</html>

Step 2: Create the JavaScript

Create an app.js file with the following code to implement the drag-and-drop functionality:

const draggable = document.getElementById('draggable');
let offsetX, offsetY;

draggable.addEventListener('mousedown', (e) => {
    offsetX = e.clientX - draggable.getBoundingClientRect().left;
    offsetY = e.clientY - draggable.getBoundingClientRect().top;
    document.addEventListener('mousemove', mouseMoveHandler);
    document.addEventListener('mouseup', mouseUpHandler);
});

function mouseMoveHandler(e) {
    draggable.style.left = `${e.clientX - offsetX}px`;
    draggable.style.top = `${e.clientY - offsetY}px`;
    draggable.style.cursor = 'grabbing'; 
}

function mouseUpHandler() {   
    document.removeEventListener('mousemove', mouseMoveHandler);
    document.removeEventListener('mouseup', mouseUpHandler);
    draggable.style.cursor = 'grab';
}

Step 3: Testing Your Drag-and-Drop Division

  1. Save both index.html and app.js files in the same directory.

  2. Open index.html in a web browser.

  3. Click and hold the “Drag me!” box, then move it around the screen.

Conclusion

You’ve successfully created a draggable division using JavaScript! This simple implementation can be expanded further with additional features like boundaries, snapping, or animations. If you have any questions or need further assistance, feel free to ask! Happy coding!

More from this blog

Blissman's thoughts

104 posts

Drag and Drop a Division Using JavaScript