Skip to content

Instantly share code, notes, and snippets.

@musou1500
Last active August 21, 2022 22:09
Show Gist options
  • Save musou1500/aef18f01fb1d7f314c30801e40a2541d to your computer and use it in GitHub Desktop.
Save musou1500/aef18f01fb1d7f314c30801e40a2541d to your computer and use it in GitHub Desktop.
<!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" />
<style>
.list {
display: flex;
width: 320px;
gap: 10px;
flex-wrap: wrap;
}
.item {
width: 100px;
height: 100px;
background-color: #ccc;
}
.item.dragging {
opacity: 0.2;
}
</style>
<script>
document.addEventListener("DOMContentLoaded", () => {
let movingItemElement = null;
const onDragStart = (ev) => {
movingItemElement = ev.target;
movingItemElement.classList.add("dragging");
};
const onDrop = (ev) => {
if (movingItemElement === null) {
return;
}
const { width } = ev.target.getBoundingClientRect();
if (ev.offsetX < width / 2) {
ev.target.before(movingItemElement);
} else {
ev.target.after(movingItemElement);
}
movingItemElement.classList.remove("dragging");
};
const onDragEnter = (ev) => {
ev.preventDefault();
};
const onDragOver = (ev) => {
ev.preventDefault();
if (movingItemElement === null) {
return;
}
const { width } = ev.target.getBoundingClientRect();
if (ev.offsetX < width / 2) {
ev.target.before(movingItemElement);
} else {
ev.target.after(movingItemElement);
}
};
const onDragEnd = () => {
if (movingItemElement !== null) {
movingItemElement.classList.remove("dragging");
movingItemElement = null;
}
};
document.querySelectorAll(".item").forEach((itemElement) => {
itemElement.addEventListener("dragenter", onDragEnter);
itemElement.addEventListener("drop", onDrop);
itemElement.addEventListener("dragover", onDragOver);
itemElement.addEventListener("dragend", onDragEnd);
itemElement.addEventListener("dragstart", onDragStart);
});
});
</script>
<title>Document</title>
</head>
<body>
<div class="list">
<div class="item" draggable="true">item1</div>
<div class="item" draggable="true">item2</div>
<div class="item" draggable="true">item3</div>
<div class="item" draggable="true">item4</div>
<div class="item" draggable="true">item5</div>
<div class="item" draggable="true">item6</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment