How To Create A Draggable Element Using Javascript
I've been spending these past few weeks trying to learn Javascript. But instead of drowning myself with YouTube tutorials, I decided to create a small project instead.
I will build some sort of a todo/kanban board web app. And I want it to have task cards that can be dragged to different columns just like post-it cards on a physical kanban board. So I needed to learn how to move HTML elements across a webpage.
Here's what I did to figure it out:
- Setup the element
This is straightforward. A div on a green background will be used to demonstrate the dragging effect.
<div class="taskCard"> Draggable div </div>
body {
background-color: green;
}
.taskCard {
background-color: orange;
min-height: 100px;
max-width: 100px;
}
2. Locate the coordinates of a mouse event
To update the location of the element as the user drags it, the coordinates of the mouse on the viewport needs to be known.
In order to demonstrate this, a mouse movement event listener was created which will display the current X and Y coordinates as the mouse moves on the browser window.
<p class="sample"></p>
let samplePar = document.querySelector('.sample');
document.addEventListener('mousemove', function(event) {
samplePar.innerText = `
Client X: ${event.clientX}
Client Y: ${event.clientY}`;
})
3. Locate the current coordinates of the element to be dragged
Updating the location of an element as it is dragged involves knowing its current position relative to its original position.
And to know the current location of an element, the method Element.getBoundingClientRect() will be used. This would give the X and Y coordinates of an element relative to the viewport via its properties (left, right, top, and bottom).
4. Calculate the new coordinates of the element and update its position in the webpage
Updating the location of the element on the browser window involves updating its left and top style attributes.
To get the updated value, the following needs to be calculated:
- Get the coordinates on where the element received the mouse down event.
- Get the coordinates on where is the current mouse move event.
- Get the difference of the two and add it to the original position of the element's bounding box.
event.target.style.left = (event.target.rectX
+ currentX - event.target.startingX + 'px');
event.target.style.top = (event.target.rectY
+ currentY - event.target.startingY + 'px');
5. An HTML element than can be dragged