Drag & Drop Functionality with JavaScript.
We'll build full drag-and-drop functionality with vanilla JavaScript where the user can drag a div from one container to another as you see it on many modern websites.
Copy the given code.
- You can copy the HTML code with the class .draggable and the attribute draggable="true" but remember that in JavaScript we have querySelectorAll for the class .container.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sortable Drag & Drop</title>
<link rel="stylesheet" href="style.css">
<script src="script.js" defer></script>
</head>
<body>
<div class="container">
<p class="draggable" draggable="true">This is the text</p>
<p class="draggable" draggable="true">13465798</p>
</div>
<div class="container">
<p class="draggable" draggable="true">~!@#$%^&*()_+</p>
<p class="draggable" draggable="true">You could put anything you want</p>
</div>
</body>
</html>
- Code for CSS. Remove the body selector if you are not copying the entire HTML and want it for a specific item.
body {
margin: 0;
}
.container {
background-color: #333;
padding: 1rem;
margin-top: 1rem;
}
.draggable {
padding: 1rem;
background-color: white;
border: 1px solid black;
cursor: move;
}
.draggable.dragging {
opacity: 0.5;
}
- Code for JavaScript.
const draggables = document.querySelectorAll(".draggable");
const containers = document.querySelectorAll(".container");
draggables.forEach((draggable) => {
draggable.addEventListener("dragstart", () => {
draggable.classList.add("dragging");
});
draggable.addEventListener("dragend", () => {
draggable.classList.remove("dragging");
});
});
containers.forEach((container) => {
container.addEventListener("dragover", (e) => {
e.preventDefault();
const afterElement = getDragAfterElement(container, e.clientY);
const draggable = document.querySelector(".dragging");
if (afterElement == null) {
container.appendChild(draggable);
} else {
container.insertBefore(draggable, afterElement);
}
});
});
function getDragAfterElement(container, y) {
const draggableElements = [
...container.querySelectorAll(".draggable:not(.dragging)"),
];
return draggableElements.reduce(
(closest, child) => {
const box = child.getBoundingClientRect();
console.log(box);
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;
}
- All set :)
Provided by Huzaifa Asim - see all
0 Comments