Skip to content

Commit f3146b6

Browse files
committed
add finished sortable list
1 parent 226720b commit f3146b6

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

77-sortable list/script.js

+60
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,67 @@ function createList() {
3737
listItems.push(listItem);
3838
draggableList.appendChild(listItem);
3939
});
40+
addListeners();
4041
}
4142

43+
function dragStart() {
44+
dragStartIndex = +this.closest("li").getAttribute("data-index");
45+
}
46+
47+
function dragEnter() {
48+
this.classList.add("over");
49+
}
50+
51+
function dragLeave() {
52+
this.classList.remove("over");
53+
}
54+
55+
function dragOver(e) {
56+
e.preventDefault(); // dragDrop is not executed otherwise
57+
}
58+
59+
function dragDrop() {
60+
const dragEndIndex = +this.getAttribute("data-index");
61+
swapItems(dragStartIndex, dragEndIndex);
62+
this.classList.remove("over");
63+
}
64+
65+
function swapItems(fromIndex, toIndex) {
66+
// Get Items
67+
const itemOne = listItems[fromIndex].querySelector(".draggable");
68+
const itemTwo = listItems[toIndex].querySelector(".draggable");
69+
// Swap Items
70+
listItems[fromIndex].appendChild(itemTwo);
71+
listItems[toIndex].appendChild(itemOne);
72+
}
73+
74+
function checkOrder() {
75+
listItems.forEach((listItem, index) => {
76+
const personName = listItem.querySelector(".draggable").innerText.trim();
77+
if (personName !== richestPeople[index]) listItem.classList.add("wrong");
78+
else {
79+
listItem.classList.remove("wrong");
80+
listItem.classList.add("right");
81+
}
82+
});
83+
}
84+
85+
// Event Listeners
86+
function addListeners() {
87+
const draggables = document.querySelectorAll(".draggable");
88+
const dragListItems = document.querySelectorAll(".draggable-list li");
89+
draggables.forEach((draggable) => {
90+
draggable.addEventListener("dragstart", dragStart);
91+
});
92+
dragListItems.forEach((item) => {
93+
item.addEventListener("dragover", dragOver);
94+
item.addEventListener("drop", dragDrop);
95+
item.addEventListener("dragenter", dragEnter);
96+
item.addEventListener("dragleave", dragLeave);
97+
});
98+
}
99+
100+
check.addEventListener("click", checkOrder);
101+
42102
// Init
43103
createList();

0 commit comments

Comments
 (0)