HomeBlogHow to create a Draggable DIV Element using JavaScript

How to create a Draggable DIV Element using JavaScript

How to create a Draggable DIV Element using JavaScript

The Draggable DIV Element is a common part of modern user interfaces (UI) today. You must have seen many websites or web apps like e-commerce, content management systems etc, on their user interface you can see functionality like the Draggable DIV element.

What is the Draggable DIV Element?

A draggable DIV element is a standard HTML <div> element that can be moved around within a web page using the mouse or touch input. If I tell simply this is a feature like the user clicks and holds the mouse button on an element and while holding it down when he moves the mouse, the element can be dragged anywhere on the web screen when the user releases the mouse button the element stops dragging.

This functionality or feature is very useful for creating interactive user interfaces, and we can make this Draggable DIV Element using HTML, CSS, and JavaScript.

Learn How to create a Draggable DIV Element using HTML, CSS, & JavaScript

In this tutorial, we will learn how to create a Draggable DIV Element using HTML, CSS, & JavaScript step-by-step.

Note: Before starting this tutorial, keep one thing in mind you should know HTML, CSS, and basic JavaScript.

Draggable DIV Element Example

Step 1: Create a Draggable DIV Element in HTML

We are starting this project by setting up the HTML file. First, create a index.html file.

Then as you can see in the below code,

  • The <body> element is identified by the ID name "drag_container" which will be our drag container or drag area.
  • Inside the <body>, I have created a <div> element with the class "draggable_div" and the ID name "draggableDiv", this will be our draggable DIV element.
  • Inside that <div> element, I have created a paragraph element with a <span> element as text content.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Draggable Div Demo</title> <link rel="stylesheet" href="style.css"> </head> <body id="drag_container"> <div class="draggable_div" id="draggableDiv"> <p>Drag <span>me at anywhere!</span></p> </div> </body> <script src="main.js"></script> </html>

Copy this HTML code and paste it into your index.html file.

Step 2: Styling the Draggable DIV Element using CSS

After structuring the HTML part let's design the Draggable Div Element using CSS for better visualisation and user experience.

Copy this CSS code and paste it into your style.css file.

css
*{ margin: 0; padding: 0; box-sizing: border-box; font-family: sans-serif; } body{ position: relative; width: 100%; height: 100vh; display: flex; justify-content: center; align-items: center; background-color: rgb(21, 21, 21); overflow: hidden; } .draggable_div{ width: 220px; height: 220px; background: linear-gradient(136deg, #FFAB5D 0%, #A257DD 100%); display: flex; justify-content: center; align-items: center; border-radius: 15px; cursor: move; transition: box-shadow .3s ease; } .draggable_div.active{ box-shadow: 0 0 20px #e9e9e9; } .draggable_div p { font-size: 28px; font-weight: 600; color: white; text-align: center; text-transform: uppercase; user-select: none; pointer-events: none; } .draggable_div p span{ color: rgb(230, 230, 230); text-transform: lowercase; }

Read also: CSS Gradient Border Glowing Animation Hover Effect

Step 3: Adding functionality to Draggable DIV Element using JavaScript

Let's break down the JavaScript code of Draggable DIV Element.

Defining some variables

The JavaScript code starts by declaring some variables.

First of all, I have created a variable whose name is dragItem, it stores the <div> element which will be draggable. Then the variable container stores the <body> element as a drag area. These two variables are created by selecting the elements by their ID names.

Similarly, I have created some more variables which are currentX, currentY, initialX, initialY, xOffset, yOffset, and state

  • currentX : This will be used to track the horizontal position of the element while dragging.
  • currentY : This will be used to track the vertical position of the while dragging.
  • initialX : This will be to track the horizontal position of the element when starts dragging.
  • initialY : This will be to track the vertical position of the element when starts dragging.
  • xOffset and yOffset : These will store the element's horizontal & vertical offset value.
  • state : It will keep tracking whether dragging is currently active.
javascript
let dragItem = document.querySelector("#draggableDiv"); let container = document.querySelector("#body"); let currentX; let currentY; let initialX; let initialY; let xOffset = 0 let yOffset = 0 let state = false;

Create the main function for Draggable DIV Element

Here I have created the main function called Draggable() and it takes two parameters,

  1. DragArea: It refers to the area where dragging is allowed.
  2. DraggableItem: It refers to the element to be dragged.
javascript
const Draggable = (DragArea, DraggableItem) => { }

Inside the Draggable function, I have created an object called events which defines event types for both mouse and touch interactions.

javascript
const events = { mouse: { dragStart: "mousedown", drag: "mousemove", dragEnd: "mouseup" }, touch: { dragStart: "touchstart", drag: "touchmove", dragEnd: "touchend" }, }

Then I created a function called deviceType() inside Draggable() function. The deviceType function checks device event types. Initially, It attempts to create a TouchEvent by document.createEvent("TouchEvent") if goes true, it returns "touch" and if goes false, it returns "mouse".

javascript
const deviceType = () => { try { document.createEvent("TouchEvent") return "touch" } catch (error) { return "mouse" } };

After that add event listeners to the dragArea element to handle the dragStart, drag, and dragEnd events. We will use specific event types for mouse or touch that are determined dynamically based on the device type detected by the device type function.

Like, in this code events[deviceType()].dragStart when the function deviceType() returns "mouse" it accesses events["mouse"] and when it returns "touch" it accesses events["touch"], then .dragStart is the property.

So when I use events[deviceType()].dragStart, first, it will access the object called events and then it will navigate to the child object either touch or mouse depending on the result of the function deviceType(). After that, it retrieves the value associated with the property called .dragStart.

For example, if the object contains dragStart: "touchstart" under the 'touch' label, using events[deviceType()].dragStart will return the string "touchstart". So, here we will apply all the functions by this method.

So, first of all, I've added an event listener for the dragStart function on DragArea, here events[deviceType()].dragStart applies the mousedown event for the mouse interaction or the touchstart event for touch interaction.

javascript
DragArea.addEventListener(events[deviceType()].dragStart, (e) => { e.preventDefault(); let eventClientX = deviceType() == "touch" ? e.touches[0].clientX : e.clientX; let eventClientY = deviceType() == "touch" ? e.touches[0].clientY : e.clientY; initialX = eventClientX - xOffset; initialY = eventClientY - yOffset; e.target == DraggableItem ? state = true : state = false; if(state){ DraggableItem.classList.add("active"); }; }, {passive: false})

Then I set up an event listener for the drag function on DragArea. Here events[deviceType()].drag applies the mousemove event for the mouse interaction or the touchmove event for the touch interaction. This function is triggered when you drag the HTML <div> element.

javascript
DragArea.addEventListener(events[deviceType()].drag, (e) => { let eventClientX = deviceType() == "touch" ? e.touches[0].clientX : e.clientX; let eventClientY = deviceType() == "touch" ? e.touches[0].clientY : e.clientY; if(state){ e.preventDefault(); currentX = eventClientX - initialX; currentY = eventClientY - initialY; xOffset = currentX; yOffset = currentY; setTranslate(currentX, currentY, DraggableItem); } }, {passive: false})

Then I set up the dragEnd event listener on the DragArea element. Here events[deviceType()].dragEnd applies the mouseup event for the mouse interaction or the touchend event for touch interaction. This function is triggered when you stop dragging or leave the HTML <div> element.

javascript
DragArea.addEventListener(events[deviceType()].dragEnd, () => { initialX = currentX; initialY = currentY; state = false; DraggableItem.classList.remove("active") })

Then I created a function named setTranslate() to handle the movement of that HTML DIV Element. Here I have defined three parameters, which are xPos, yPos, and el.

  • xPos: representing the horizontal position.
  • yPos: representing the vertical position.
  • el: representing the HTML element.

This function will apply CSS transform using the translate3d() function. Which will translate the element along the x and y axes by the values of xPos and yPos respectively, and the value of the z-axis will be 0.

javascript
function setTranslate(xPos, yPos, el) { el.style.transform = `translate3d(${xPos}px, ${yPos}px, 0)`; };

So now we have completely created our Draggable() function, it's time to run the function.

Run this function and as we have defined it accepts two parameters. It takes two parameters which are container and dragItem.

javascript
Draggable(container, dragItem);

Here is the full JavaScript code given below, copy the code and paste it into your JavaScript file.

javascript
let dragItem = document.querySelector("#draggableDiv"); let container = document.querySelector("#body"); let currentX; let currentY; let initialX; let initialY; let xOffset = 0 let yOffset = 0 let state = false; const Draggable = (DragArea, DraggableItem) => { const events = { mouse: { dragStart: "mousedown", drag: "mousemove", dragEnd: "mouseup" }, touch: { dragStart: "touchstart", drag: "touchmove", dragEnd: "touchend" }, } const deviceType = () => { try { document.createEvent("TouchEvent") return "touch" } catch (error) { return "mouse" } }; DragArea.addEventListener(events[deviceType()].dragStart, (e) => { e.preventDefault(); let eventClientX = deviceType() == "touch" ? e.touches[0].clientX : e.clientX; let eventClientY = deviceType() == "touch" ? e.touches[0].clientY : e.clientY; initialX = eventClientX - xOffset; initialY = eventClientY - yOffset; e.target == DraggableItem ? state = true : state = false; if(state){ DraggableItem.classList.add("active"); }; }, {passive: false}) DragArea.addEventListener(events[deviceType()].drag, (e) => { let eventClientX = deviceType() == "touch" ? e.touches[0].clientX : e.clientX; let eventClientY = deviceType() == "touch" ? e.touches[0].clientY : e.clientY; if(state){ e.preventDefault(); currentX = eventClientX - initialX; currentY = eventClientY - initialY; xOffset = currentX; yOffset = currentY; setTranslate(currentX, currentY, DraggableItem); } }, {passive: false}) DragArea.addEventListener(events[deviceType()].dragEnd, () => { initialX = currentX; initialY = currentY; state = false; DraggableItem.classList.remove("active") }) function setTranslate(xPos, yPos, el) { el.style.transform = `translate3d(${xPos}px, ${yPos}px, 0)`; }; } Draggable(container, dragItem);

After adding this JavaScript code, now you can drag your draggable div element and move around within the web page using mouse or touch input.

So this is the tutorial about How to create a Draggable Div Element using HTML, CSS, & JavaScript.

Read also: Email Input Validation using HTML, CSS, & JavaScript