Skip to content

Commit 323e78d

Browse files
committed
drap and drop feature using vanilla js.
1 parent b2f1a8c commit 323e78d

File tree

3 files changed

+89
-0
lines changed

3 files changed

+89
-0
lines changed

drag-drop/index.html

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
4+
<head>
5+
<meta charset="UTF-8">
6+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7+
<link rel="stylesheet" href="style.css">
8+
<script src="script.js" defer></script>
9+
<title>Drag & Drop</title>
10+
</head>
11+
12+
<body>
13+
14+
</body>
15+
<div class="container">
16+
<p class="draggable" draggable="true">1</p>
17+
<p class="draggable" draggable="true">2</p>
18+
</div>
19+
20+
<div class="container">
21+
<p class="draggable" draggable="true">3</p>
22+
<p class="draggable" draggable="true">4</p>
23+
</div>
24+
25+
</html>

drag-drop/script.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
const draggables = document.querySelectorAll('.draggable');
2+
const containers = document.querySelectorAll('.container');
3+
4+
draggables.forEach(draggable => {
5+
draggable.addEventListener('dragstart', () => {
6+
draggable.classList.add('dragging');
7+
});
8+
9+
draggable.addEventListener('dragend', () => {
10+
draggable.classList.remove('dragging');
11+
});
12+
});
13+
14+
containers.forEach(container => {
15+
container.addEventListener('dragover', e => {
16+
e.preventDefault();
17+
const afterElement = getDragAfterElement(container, e.clientY);
18+
const draggable = document.querySelector('.dragging');
19+
if (afterElement == null) {
20+
container.appendChild(draggable);
21+
} else {
22+
container.insertBefore(draggable, afterElement);
23+
}
24+
});
25+
});
26+
27+
function getDragAfterElement(container, y) {
28+
const draggableElements = [
29+
...container.querySelectorAll('.draggable:not(.dragging)')
30+
];
31+
32+
return draggableElements.reduce(
33+
(closest, child) => {
34+
const box = child.getBoundingClientRect();
35+
const offset = y - box.top - box.height / 2;
36+
if (offset < 0 && offset > closest.offset) {
37+
return { offset: offset, element: child };
38+
} else {
39+
return closest;
40+
}
41+
},
42+
{ offset: Number.NEGATIVE_INFINITY }
43+
).element;
44+
}

drag-drop/style.css

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
body {
2+
margin: 0;
3+
}
4+
5+
.container {
6+
background-color: #333;
7+
padding: 1rem;
8+
margin-top: 1rem;
9+
}
10+
11+
.draggable {
12+
padding: 1rem;
13+
background-color: white;
14+
border: 1px solid black;
15+
cursor: move;
16+
}
17+
18+
.draggable.dragging {
19+
opacity: 0.5;
20+
}

0 commit comments

Comments
 (0)