HomeJavascriptDraggable Element With Javascript

Draggable Element With Javascript

Hey everyone. Welcome to today’s tutorial. In today’s tutorial, we will learn how to create a simple draggable element. To build this project, we need HTML, CSS and Javascript.

Let us take a look at how this project works. This project consists of a div element placed on the webpage. The user can use their mouse cursor to hold and drag this div anywhere on the webpage. Even though we have just made a simple div draggable, you can go ahead and use other elements within this div.

If you are looking for more tutorials to improve your javascript skills you can check out this playlist here. This playlist consists of 100+ javascript projects. The difficulty level of these projects varies from simple to quite complex ones. Hence this playlist is suitable for all kinds of javascript learners including javascript beginners to javascript beginners.

Video Tutorial:

If you are interested to learn by watching a video tutorial rather than reading this blog post you can check out this video down below. Also, subscribe to my youtube channel, where I post new tips, tricks and tutorials related to web development every alternate day.

Project Folder Structure:

Before we start coding, let us take a look at the project folder structure. We create a project folder called – ‘Draggable Div’. Inside this folder, we have three files. These files are – index.html, style.css and script.js.

The first file is the HTML document. Next, we have the stylesheet, and finally, we have the script file.

HTML:

We begin with the HTML code. First. copy the code provided to you below and paste it into your HTML document.

The HTML code creates an element that builds the structure of our project. In our case, the HTML code consists of a div with id-‘container’. Inside the container, we have a div with id – ‘draggable-elem’. You can have any kind of element inside this div. I have used a simple paragraph tag.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Draggable Div</title>
    <!-- Google Fonts -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@500&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div id="container">
      <div id="draggable-elem">
        <p>Drag Me</p>
      </div>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

CSS:

We now style the elements created with HTML using CSS. The styling is completely optional. You can either skip it or customize the div according to your choice. Now copy the code provided to you below and paste it into your stylesheet.

body {
  padding: 0;
  margin: 0;
  background: linear-gradient(135deg, #c3a3f1, #6414e9);
}
#container {
  height: 100vh;
  width: 100vw;
  position: relative;
}
#draggable-elem {
  position: absolute;
  background-color: #ffffff;
  font-size: 1.6em;
  width: 7em;
  height: 7em;
  position: absolute;
  transform: translate(-50%, -50%);
  left: 50%;
  top: 50%;
  display: grid;
  place-items: center;
  font-family: "Poppins", sans-serif;
  border-radius: 0.3em;
  cursor: move;
}

Javascript:

We finally implement the functionality using Javascript. For this copy the code below and paste it into your script file. I have added comments for an explanation for each line of code to make it easier for you to understand.

let draggableElem = document.getElementById("draggable-elem");
let initialX = 0,
  initialY = 0;
let moveElement = false;

//Events Object
let events = {
  mouse: {
    down: "mousedown",
    move: "mousemove",
    up: "mouseup",
  },
  touch: {
    down: "touchstart",
    move: "touchmove",
    up: "touchend",
  },
};

let deviceType = "";

//Detech touch device
const isTouchDevice = () => {
  try {
    //We try to create TouchEvent (it would fail for desktops and throw error)
    document.createEvent("TouchEvent");
    deviceType = "touch";
    return true;
  } catch (e) {
    deviceType = "mouse";
    return false;
  }
};

isTouchDevice();

//Start (mouse down / touch start)
draggableElem.addEventListener(events[deviceType].down, (e) => {
  e.preventDefault();
  //initial x and y points
  initialX = !isTouchDevice() ? e.clientX : e.touches[0].clientX;
  initialY = !isTouchDevice() ? e.clientY : e.touches[0].clientY;

  //Start movement
  moveElement = true;
});

//Move
draggableElem.addEventListener(events[deviceType].move, (e) => {
  //if movement == true then set top and left to new X andY while removing any offset
  if (moveElement) {
    e.preventDefault();
    let newX = !isTouchDevice() ? e.clientX : e.touches[0].clientX;
    let newY = !isTouchDevice() ? e.clientY : e.touches[0].clientY;
    draggableElem.style.top =
      draggableElem.offsetTop - (initialY - newY) + "px";
    draggableElem.style.left =
      draggableElem.offsetLeft - (initialX - newX) + "px";
    initialX = newX;
    initialY = newY;
  }
});

//mouse up / touch end
draggableElem.addEventListener(
  events[deviceType].up,
  (stopMovement = (e) => {
    moveElement = false;
  })
);

draggableElem.addEventListener("mouseleave", stopMovement);
draggableElem.addEventListener(events[deviceType].up, (e) => {
  moveElement = false;
});

That’s it for this tutorial. If you face any issues while creating this code you can download the source code by clicking on the – ‘Download Code’ button below. Also, I would love to hear from you guys, so if you have any queries, suggestions, or feedback, you can comment below.
Happy Coding!

 

Previous articleMCQ – 14/8/22
Next articleMCQ – 16/8/22
RELATED ARTICLES

2 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here

17 + 14 =

Most Popular