JavaScript Drag and Drop Div with Example

JavaScript Drag And Drop Div. With Example
Project: drag and drop small library created by java script (js)
Author: Hossein
Edit Online: View on CodePen
License: MIT

This JavaScript code example sets up a drag and drop functionality for a list of draggables div elements that can be dragged and dropped into different containers. The first part of the code adds event listeners to the draggables to change their opacity while dragging.

The second part of the code adds an event listener to the containers for when an item is being dragged over them, which determines where the dragged item should be inserted into the container based on its position relative to the other items in the container.

The dragAfterElement function calculates the position of the element that the dragged item should be inserted after, based on the current position of the mouse cursor.

How to Create Drag and Drop Functionality

First of all, create two containers with the class name “draggable-container” and place any element inside them with a class name “shallow-draggable”. Define the draggable attribute with the value “true”. The complete HTML structure for draggable divs is as follows:

<div class="draggable-container">
      <h1 class="title">Pick from here</h1>
      <p class="shallow-draggable" draggable="true">1</p>
      <p class="shallow-draggable" draggable="true">2</p>
    </div>
    <div class="draggable-container">
      <h1 class="title">Put it here !!!</h1>
      <p class="shallow-draggable" draggable="true">3</p>
      <p class="shallow-draggable" draggable="true">4</p>
    </div>

Style using the following CSS styles:

@import url("https://fonts.googleapis.com/css2?family=Golos+Text:wght@500&display=swap");

body {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  background-color: #5c3d7028;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  font-family: "Golos Text";
  margin-top: 5rem;
}

.title {
  color: #e5e0e8;
  padding: 0;
  margin: 0;
  font-weight: 400;
}

p {
  color: #1e1028;
}

.draggable-container {
  background-color: #1e1028;
  padding: 3rem;
  margin: 1rem 0;
  width: 70%;
  border-radius: 5px;
  box-shadow: 10px 15px 20px #1e192844;
}

.shallow-draggable {
  background-color: #f1edf3;
  color: #29262b;
  padding: 1rem;
  margin-top: 2rem;
  border-radius: 5px;
  transition: opacity 200ms ease;
}

.dragging {
  opacity: 0.5;
  transition: opacity 1s ease;
}

Finally, add the following JavaScript function to activate the drag and drop div functionality:

const draggbles = document.querySelectorAll(".shallow-draggable")
const containers = document.querySelectorAll(".draggable-container")

draggbles.forEach((draggble) => {
  //for start dragging costing opacity
  draggble.addEventListener("dragstart", () => {
    draggble.classList.add("dragging")
  })

  //for end the dragging opacity costing
  draggble.addEventListener("dragend", () => {
    draggble.classList.remove("dragging")
  })
})
//shit
containers.forEach((container) => {
  container.addEventListener("dragover", function (e) {
    e.preventDefault()
    const afterElement = dragAfterElement(container, e.clientY)
    const dragging = document.querySelector(".dragging")
    if (afterElement == null) {
      container.appendChild(dragging)
    } else {
      container.insertBefore(dragging, afterElement)
    }
  })
})

function dragAfterElement(container, y) {
  const draggbleElements = [...container.querySelectorAll(".shallow-draggable:not(.dragging)")]

  return draggbleElements.reduce(
    (closest, child) => {
      const box = child.getBoundingClientRect()
      const offset = y - box.top - box.height / 2
      if (offset < 0 && offset > closest.offset) {
        return { offset: offset, element: child }
      } else {
        return closest
      }
    },
    { offset: Number.NEGATIVE_INFINITY }
  ).element
}

That’s all! hopefully, you have successfully integrated this Javascript code example to create a drag and drop div into another div. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *