HomeCSSSimple Drag and Drop Element With Javascript

Simple Drag and Drop Element With Javascript

Introduction:

Have you ever wanted to create a simple drag and drop interface for your web application? In this tutorial, we’ll walk through how to build a basic drag and drop feature using HTML, CSS, and JavaScript. This interactive feature can enhance user experience and make your web application more engaging. By the end of this tutorial, you will have a functional drag and drop interface that can be used on both desktop and touch devices.

Things You Will Learn:

  1. Detecting the device type (mouse or touch) to ensure compatibility.
  2. Implementing drag and drop functionality using HTML, CSS, and JavaScript.
  3. Creating a responsive design for both desktop and touch devices.

Video Tutorial:

Do take a look at my YouTube channel. Whether you are looking to start a new career or just looking to enhance your existing skill set, we have got you covered. Subscribe now and take your first step towards becoming a professional web developer!

Project Folder Structure:

Now before we move on to actual coding we create a project folder structure. We name the project folder as – ”Drag & Drop Element”. Within this folder we have 3 files. These files are:

  • index.html
  • style.css
  • script.js

HTML:

We begin with the HTML code. Copy the code below and paste it into your HTML document.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Drag & Drop Element</title>
    <!--- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div id="draggable-object" draggable="true"></div>
    <div id="drop-point"></div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

 

CSS:

Next, we style our game using CSS. For this copy, the code provided to you below and paste it into your stylesheet.

body {
  background-color: #e5edfa;
}
.hide {
  display: none;
}
#draggable-object {
  background-color: #006eff;
  width: 9em;
  height: 9em;
  border-radius: 0.5em;
  cursor: move;
}
#drop-point {
  height: 10em;
  width: 10em;
  border: 2px dashed #000000;
  background-color: aliceblue;
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  border-radius: 0.5em;
  display: flex;
  align-items: center;
  justify-content: center;
}

 

JS:

Finally, we add functionality using Javascript. For this once again copy the code below and paste it into your script file.

const dragObject = document.querySelector("#draggable-object");
const dropContainer = document.querySelector("#drop-point");
let deviceType = "";
let initialX = 0,
  initialY = 0;
let currentElement = "";
let moveElement = false;

//Detect 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;
  }
};

//Drag and drop functions

function dragStart(e) {
  if (isTouchDevice()) {
    initialX = e.touches[0].clientX;
    initialY = e.touches[0].clientY;
    //Start movement for touch
    moveElement = true;
    currentElement = e.target;
  } else {
    e.dataTransfer.setData("text", e.target.id);
  }
}

function dragOver(e) {
  e.preventDefault();
}

//For touchscreen movement
const touchMove = (e) => {
  if (moveElement) {
    e.preventDefault();
    let newX = e.touches[0].clientX;
    let newY = e.touches[0].clientY;

    dragObject.style.top = dragObject.offsetTop - (initialY - newY) + "px";
    dragObject.style.left = dragObject.offsetLeft - (initialX - newX) + "px";
    initialX = newX;
    initialY = newY;
  }
};

const drop = (e) => {
  e.preventDefault();
  //For touch screen
  if (isTouchDevice()) {
    moveElement = false;
    //Get boundaries of div
    const currentDropBound = dropContainer.getBoundingClientRect();
    if (
      initialX >= currentDropBound.left &&
      initialX <= currentDropBound.right &&
      initialY >= currentDropBound.top &&
      initialY <= currentDropBound.bottom
    ) {
      dragObject.classList.add("hide");
      dropContainer.insertAdjacentHTML(
        "afterbegin",
        '<div id="draggable-object"></div>'
      );
    }
  } else {
    if (e.target.id == "drop-point") {
      dragObject.setAttribute("draggable", "false");

      dragObject.classList.add("hide");
      e.target.insertAdjacentHTML(
        "afterbegin",
        '<div id="draggable-object"></div>'
      );
    }
  }
};

window.onload = async () => {
  currentElement = "";
  dragObject.innerHTML = "";
  dropContainer.innerHTML = "";

  if (isTouchDevice) {
    dragObject.style.position = "absolute";
  }

  dragObject.addEventListener("dragstart", dragStart);
  //for touch screen
  dragObject.addEventListener("touchstart", dragStart);
  dragObject.addEventListener("touchend", drop);
  dragObject.addEventListener("touchmove", touchMove);

  dropContainer.addEventListener("dragover", dragOver);
  dropContainer.addEventListener("drop", drop);
};

 

Conclusion:

Congratulations! You’ve successfully created a simple drag and drop interface for your web application. This feature can be a valuable addition to your project, allowing users to interact with your content in a more engaging way. Remember to customize the styles and expand on this foundation to suit your specific needs.

Thank you for joining us in this tutorial, and we hope you found it informative and helpful. Happy coding!

Previous articleImage Loading Blur Effect
Next articleScoreboard
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

fifteen + 17 =

Most Popular

Dynamic color changer

Fruit Fall Game Javascript

Butterfly CSS Art