<html>
<head>
<style>
body {
font-family: 'Poppins', sans-serif;
padding: 20px;
background: linear-gradient(to right, #6a11cb, #2575fc);
color: #fff;
text-align: center;
}
h2 {
margin-bottom: 20px;
font-size: 1.8em;
}
.list {
list-style: none;
padding: 0;
width: 350px;
margin: auto;
background: rgba(255, 255, 255, 0.1);
border-radius: 10px;
box-shadow: 0 8px 15px rgba(0, 0, 0, 0.2);
}
.item {
padding: 15px 20px;
margin: 8px 0;
background: rgba(255, 255, 255, 0.8);
border-radius: 5px;
font-size: 1.1em;
color: #333;
font-weight: bold;
cursor: grab;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
transition: background 0.2s, transform 0.2s;
}
.item:hover {
background: #e8f0ff;
transform: scale(1.03);
}
.dragging {
opacity: 0.7;
transform: rotate(-2deg);
}
.over {
border: 2px dashed #ff8c42;
background: #fff3e0;
}
</style>
</head>
<body>
<h2>Drag and Drop Sortable List</h2>
<ul class="list">
<li class="item" draggable="true">Item 1</li>
<li class="item" draggable="true">Item 2</li>
<li class="item" draggable="true">Item 3</li>
<li class="item" draggable="true">Item 4</li>
<li class="item" draggable="true">Item 5</li>
</ul>
<script defer>
const list = document.querySelector('.list');
let dragging = null;
if (list) {
list.addEventListener('dragstart', function (e) {
const target = e.target;
if (target && target.classList.contains('item')) {
dragging = target;
target.classList.add('dragging');
}
});
list.addEventListener('dragend', function () {
if (dragging) {
dragging.classList.remove('dragging');
}
document.querySelectorAll('.item').forEach(function (item) {
item.classList.remove('over');
});
dragging = null;
});
list.addEventListener('dragover', function (e) {
e.preventDefault();
const afterElement = getDragAfterElement(list, e.clientY);
document.querySelectorAll('.item').forEach(function (item) {
item.classList.remove('over');
});
if (afterElement && dragging) {
afterElement.classList.add('over');
list.insertBefore(dragging, afterElement);
} else if (dragging) {
list.appendChild(dragging);
}
});
}
function getDragAfterElement(container, y) {
const items = Array.from(container.querySelectorAll('.item:not(.dragging)'));
return items.reduce(function (closest, child) {
const box = child.getBoundingClientRect();
const offset = y - box.top - box.height / 2;
if (offset < 0 && offset > closest.offset) {
return { offset, element: child };
}
return closest;
}, { offset: Number.NEGATIVE_INFINITY, element: null }).element;
}
</script>
</body>
</html>