-1

I used document.querySelectorAll() get a NodeList of all buttons in the HTML file, then iterated through each button to add an event listener to each button to listen for a click on each button.

document.querySelectorAll("button").forEach(node => {
  node.addEventListener("click", console.log("Button clicked"));
});

However, on load, all buttons are clicked, and I do not understand why this is happening.

eg3
  • 25
  • 2
  • 6
  • 1
    Does this answer your question? [addEventListener calls the function without me even asking it to](https://stackoverflow.com/questions/16310423/addeventlistener-calls-the-function-without-me-even-asking-it-to) – Sebastian Simon Jul 14 '21 at 16:05
  • 1
    the second argument of `addEventListener` must be a function - replace `console.log("Button clicked")` with `() => console.log("Button clicked")` – Robin Zigmond Jul 14 '21 at 16:06

1 Answers1

0

The function attached should be a handler, executed by the event listener when required. In your given example, the console.log() is called when the foreach function is called.

Change your handler function to accept an argument, then perform your console.log:

document.querySelectorAll("button").forEach(node => {
  node.addEventListener("click", function(ev){ console.log('Clicked'); });
});

I used a function here for readability but it can be any valid callback. https://developer.mozilla.org/en-US/docs/Web/API/EventListener#javascript

Glycerine
  • 7,157
  • 4
  • 39
  • 65