Unable to load the content

Please attempt to reload the page or alternatively, try accessing it using a different browser.

Drag Me Anywhere: Create draggable Element using JavaScript

In modern web development, providing users with an intuitive and interactive interface is crucial. One way to achieve this is by implementing draggable elements, allowing users to easily move and rearrange content. In this tutorial, we'll explore how to create a draggable element using HTML, CSS, and JavaScript.

Drag-Me-Anywhere-Create-draggable-Element-using-JavaScript

Also Read: Custom Volume Slider using HTML CSS and JS

HTML Structure

 <div class="container">
    <div class="draggableElement">Drag me!</div>
</div>

Container (<div class="container">): This serves as the outer container for our draggable element. It provides a boundary within which the draggable element can be moved.

Draggable Element (<div class="draggableElement">): This is the core element that users can interact with. It's the part that users will click and drag around the screen.

CSS Styling

Now, let's explore the CSS styling applied to our elements to make them visually appealing and provide a smooth user experience.

.container, .draggableElement{
    display: flex;
    align-items: center;
    justify-content: center;
}

.container {
    min-height: 100vh;
    min-width: 250px;
    position: relative;
}

.draggableElement {
    position: absolute;
    cursor: grab;
    width: 150px;
    height: 150px;
    font-size: 18px;
    color: #fff;
    border-radius: 30px;
    font-family: 'Calibri';
    transition: transform .3s;
    background-color: #10344d;
}

.dragging {
    transform: scale(.9);
    cursor: grabbing !important;
}

This CSS defines the visual aspects of our draggable element, including its size, color, and the transition effect when dragged.

JavaScript Implementation 

Now, let's explore the JavaScript code responsible for making our element draggable.

Initialization

const draggableElement = document.querySelector('.draggableElement');
let offsetX = 0, offsetY = 0;

We start by selecting the HTML element that we want to make draggable. Initialize variables offsetX and offsetY to store the initial offset of the mouse pointer from the top-left corner of the draggable element.

MouseDown Event Listener

draggableElement.addEventListener('mousedown', function (e) {
    // Preventing default behavior to avoid unwanted selections
    e.preventDefault();

    // Calculating initial offsets
    offsetX = e.clientX - draggableElement.getBoundingClientRect().left;
    offsetY = e.clientY - draggableElement.getBoundingClientRect().top;

    // Adding the 'dragging' class to apply styling changes
    draggableElement.classList.add('dragging');

    // Adding event listeners for mousemove and mouseup
    document.addEventListener('mousemove', dragElement);
    document.addEventListener('mouseup', stopDragging);
});

This event listener triggers when the mouse button is pressed down on the draggable element. It prevents the default behavior to avoid text selection or other unwanted actions. It calculates the initial offset by subtracting the current mouse position from the top-left corner of the element.

The 'dragging' class is added to apply styling changes during dragging.Event listeners for mousemove and mouseup are added to track the movement and release of the mouse.

Drag Element Function

function dragElement(e) {
    // Updating the element's position based on mouse movements
    draggableElement.style.left = `${e.clientX - offsetX}px`;
    draggableElement.style.top = `${e.clientY - offsetY}px`;
}

This function is called during the mousemove event. It updates the position of the draggable element based on the difference between the current mouse position and the initial offset.

Also Read: HTML CSS JS Project: Quiz web App using JavaScript

Stop Dragging Function

function stopDragging(e) {
    // Preventing default behavior to avoid unwanted selections
    e.preventDefault();

    // Removing the 'dragging' class to revert styling changes
    draggableElement.classList.remove('dragging');

    // Removing event listeners to stop tracking mouse movements
    document.removeEventListener('mousemove', dragElement);
    document.removeEventListener('mouseup', stopDragging);
}

This function is called when the mouse button is released (mouseup event). It prevents the default behavior to avoid unwanted selections. The 'dragging' class is removed to revert styling changes made during dragging. Event listeners for mousemove and mouseup are removed to stop tracking mouse movements.

The draggable element's behavior is orchestrated through event listeners for mouse actions (mousedown, mousemove, mouseup). The calculations involving initial offsets and continuous updates to the element's position create the seamless dragging effect. 

The styling changes, such as adding the 'dragging' class, enhance the visual feedback during the dragging process. Understanding this working mechanism is pivotal for implementing similar interactive features in web development.

Download