I want to build a function to toggle/untoggle all items of a list (populateList()
is a separate function to write the actual html):
function toggleAll(event, check) {
items.forEach(item => {
if (check === "check") {
item.done = true;
} else {
item.done = false;
}
});
localStorage.setItem("items", JSON.stringify(items));
populateList(items, itemsList);
}
When clicking on the according buttons (checkAll
/uncheckAll
) the function should be fired:
const checkAll = document.querySelector(".check");
const uncheckAll = document.querySelector(".uncheck");
checkAll.addEventListener("click", toggleAll("check"));
uncheckAll.addEventListener("click", toggleAll("uncheck"));
Apparently this does not work. For some reasons the function toggleAll
is run only once at page load, the buttons do not react. I tried to pass the event itself with the following code:
checkAll.addEventListener("click", (event) => toggleAll(event, "check"));
uncheckAll.addEventListener("click", (event) => toggleAll(event, "uncheck"));
This works just fine! I have no clue why. Could somebody please enlighten me on this? What am I overlooking here?