document.addEventListener(‘DOMContentLoaded’, function() {
const container = document.querySelector(‘.sortable-container’);
const items = document.querySelectorAll(‘.item’);
items.forEach(item => {
item.addEventListener(‘dragstart’, handleDragStart);
item.addEventListener(‘dragend’, handleDragEnd);
});
container.addEventListener(‘dragover’, handleDragOver);
container.addEventListener(‘drop’, handleDrop);
});
function handleDragStart(e) {
e.dataTransfer.setData(‘text/plain’, this.id);
}
function handleDragEnd(e) {
// Clean up the placeholder
const container = document.querySelector(‘.sortable-container’);
const placeholders = container.querySelectorAll(‘.placeholder’);
placeholders.forEach(placeholder => placeholder.remove());
}
function handleDragOver(e) {
e.preventDefault();
const container = document.querySelector(‘.sortable-container’);
// Create a temporary div to serve as a placeholder
const tempDiv = document.createElement(‘div’);
tempDiv.className = ‘placeholder’;
tempDiv.style.width = `${e.target.offsetWidth}px`;
// Find the correct position to insert the dragged item
const items = container.querySelectorAll(‘.item:not(.placeholder)’);
let insertPosition;
if (e.clientY > container.offsetTop + container.offsetHeight / 2) {
insertPosition = ‘bottom’;
} else {
insertPosition = ‘top’;
}
// Insert the placeholder before or after the target
const target = document.querySelector(`#${e.dataTransfer.getData(‘text/plain’)}`);
if (insertPosition === ‘bottom’ && target) {
container.insertBefore(tempDiv, target);
} else if (insertPosition === ‘top’ && target) {
container.insertBefore(tempDiv, target.nextSibling);
}
}
function handleDrop(e) {
e.preventDefault();
const draggedId = e.dataTransfer.getData(‘text/plain’);
const draggedItem = document.getElementById(draggedId);
// Remove the placeholder
const placeholders = document.querySelectorAll(‘.placeholder’);
placeholders.forEach(placeholder => placeholder.remove());
// Insert the dragged item into the correct position
if (e.clientY > container.offsetTop + container.offsetHeight / 2) {
container.appendChild(draggedItem);
} else {
const firstHalfItems = Array.from(items).slice(0, items.length / 2);
const foundIndex = firstHalfItems.findIndex(item => item.id === draggedId);
if (foundIndex !== –1) {
container.insertBefore(draggedItem, firstHalfItems[foundIndex].nextSibling);
}
}
// Update the order in your data structure
const newOrder = Array.from(container.querySelectorAll(‘.item’)).map(item => item.id);
updateSortState(newOrder);
}
function updateSortState(order) {
console.log(‘New order:’, order);
// Here you can save the order to localStorage or send it to your backend
}
Leave a Reply
You must be logged in to post a comment.