Skip to content

Commit

Permalink
Adds Drag and Drop Feature
Browse files Browse the repository at this point in the history
  • Loading branch information
Abhijitkr committed Oct 3, 2023
1 parent 68ff29b commit 5f3c4b6
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
36 changes: 35 additions & 1 deletion script.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
var ul = document.getElementById('todos');
var todos = new Set(); // Collection to store added todos
var draggedItem = null;

var addButton = document.getElementById('add');
addButton.addEventListener('click', addItem);
Expand Down Expand Up @@ -188,6 +189,7 @@ function addItemToUI(itemId, item, checked) {

// Apply animation to the newly added
li.classList.add('animation');
li.setAttribute('draggable', 'true');
}

function updateDatabase(event) {
Expand All @@ -208,4 +210,36 @@ function updateDatabase(event) {
}
};
xhr.send('id=' + itemId + '&checked=' + isChecked + '&text=' + encodeURIComponent(text));
}
}

ul.addEventListener('dragstart', function (event) {
if (event.target.tagName === 'LI') {
draggedItem = event.target;
event.dataTransfer.setData('text/plain', ''); // Required for Firefox
}
});

ul.addEventListener('dragover', function (event) {
event.preventDefault();
});

ul.addEventListener('drop', function (event) {
event.preventDefault();
if (draggedItem && event.target.tagName === 'LI') {
// Swap the positions of the dragged item and the drop target
const dropTarget = event.target;
const dropTargetIndex = Array.from(ul.children).indexOf(dropTarget);
const draggedIndex = Array.from(ul.children).indexOf(draggedItem);

if (dropTargetIndex !== -1 && draggedIndex !== -1) {
// Remove the animation class before swapping to prevent glitches
draggedItem.classList.remove('animation');
ul.insertBefore(draggedItem, dropTargetIndex > draggedIndex ? dropTarget.nextSibling : dropTarget);
// Add animation class after swapping for smooth transition
setTimeout(() => {
draggedItem.classList.add('animation');
}, 0);
}
}
draggedItem = null;
});
5 changes: 5 additions & 0 deletions style.css
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@
margin-bottom: 10px;
padding: 8px;
transition: border-color 0.3s ease-in-out;
transition: transform 0.2s ease-in-out;
}

.todo-list li label {
Expand Down Expand Up @@ -207,5 +208,9 @@

li.animation {
animation: dropAnimation 0.5s ease-in-out;
transform: scale(1.05);
}

li.dragged-over {
background-color: #f0f0f0; /* Change background color when dragged over */
}

0 comments on commit 5f3c4b6

Please sign in to comment.