Spot the bug - #150: Save Button Click

Quick one: event handling bug here.

const button = document.querySelector('#save');
button.addEventListener('click', saveForm());

function saveForm() {
  console.log('saved');
}

Reply with what is broken and how you would fix it.

saveForm() calls it immediately. you want to pass the function reference, not the result of calling it. so button.addEventListener('click', saveForm);

Spot the Bug answer: The saveForm function is called immediately instead of being passed as a reference to the event listener.

The fix:

button.addEventListener('click', saveForm);

Why:
When saveForm() is used, the parentheses cause the function to execute right away, and its return value (which is undefined) is then passed to addEventListener. The event listener expects a function reference to call when the event occurs, not the result of an immediate function execution.

First-answer leaderboard

  1. @kirupa - 8 (firsts) :trophy:
  2. @Apexcodes - 6 (firsts)
  3. @emmawalter5 - 6 (firsts)
  4. @adnanahmed - 2 (firsts)