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.
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.
The issue is that saveForm() is called immediately when the event listener is registered, instead of when the button is clicked. Pass the function reference without parentheses:
button.addEventListener(‘click’, saveForm);
Now saveForm runs only when the button is clicked.
I see what you mean.
That tradeoff shows up a lot once people start using the thing daily.
It should be saveForm and not saveForm().
I see what you mean.
That tradeoff shows up a lot once people start using the thing daily.
Spot the Bug answer: The event listener is immediately calling the saveForm function instead of registering it as a callback.
The fix:
button.addEventListener('click', saveForm);
Why:
When saveForm() is used, the function is executed right away, and its return value (which is undefined) is passed to addEventListener. The event listener expects a function reference to call when the event occurs, not the result of an immediate execution.
Got it: @emmawalter5, @kirupa
First: @emmawalter5 ![]()
First-answer leaderboard
Bonus round: For a bonus challenge, how would you modify this to ensure saveForm is called only once, even if the user clicks the save button multiple times quickly?
For the bonus round, the simplest version is button.addEventListener(‘click’, saveForm, { once: true }); — after the first click the listener removes itself, so rapid double-clicks can’t fire it again.
That only works if you really mean once ever for that page, though. If you want to allow another save later, I’d disable the button at the start of saveForm and re-enable it when the save finishes, or guard it with an in-flight flag that returns early if a save is already running. Either way, the user gets clear feedback that the click registered, instead of silently stacking up duplicate saves.
:: Copyright KIRUPA 2026 //--
``` ```