0

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Sebastian
  • 7
  • 1
  • 6
  • `checkAll.addEventListener("click", toggleAll("check"));` **calls** `toggleAll("check")` and passes its return value into `addEventListener`, exactly the way `foo(bar())` **calls** `bar()` and passes its return value to `foo`. `checkAll.addEventListener("click", (event) => toggleAll(event, "check"));` creates an arrow function (`(event) => toggleAll(event, "check")`) that will call `toggleAll` when it's called. – T.J. Crowder Mar 11 '21 at 13:03
  • thanks for the swift comment. I still dont get why it does not work with only checkAll.addEventListener("click", toggleAll("check")); – Sebastian Mar 11 '21 at 13:12
  • You need to pass a function into `addEventListener` as its second argument. `checkAll.addEventListener("click", toggleAll("check"));` doesn't do that. Instead, again, it **calls** `toggleAll("check")` and passes its return value into `addEventListener`. So instead of hooking up a handler to be called later when the event occurs, you've **called** the handler right away (and only passed it one argument, where it expects two). – T.J. Crowder Mar 11 '21 at 13:22
  • thanks for clarification! I thought `toggleAll("check")` is a function. btw. also when I defined the function with one argument `function toggleAll(check)` it did not work either... – Sebastian Mar 11 '21 at 13:36
  • No, `toggleAll("check")` is a function **call**. `toggleAll` is a function. – T.J. Crowder Mar 11 '21 at 13:52
  • 1
    After re-reading it 2 weeks later, I fully understand now. Makes total sense - many thanks @T.J.Crowder – Sebastian Mar 29 '21 at 08:07

0 Answers0