Unit 6 · JavaScript in the page
Why addEventListener runs your function at once
Brackets call a function right now. addEventListener('click', showHours()) runs showHours while the page loads and passes along its result. Pass the function itself, showHours, so the browser can run it later, on each click.
The mix-up
What people often think
“You plug in a function by writing it with brackets, like addToCart().”
What the tutor says
Brackets run the function right now, while the page loads. Hand over the name, addToCart, so the browser can run it later.
If addToCart() runs while the page loads, what happens when someone clicks later?
How it works
A tell-tale sign: whatever the click should do has already happened when the page appears, and clicking does nothing.
The brackets are the bug wherever they sit, whether in addEventListener or onclick. Hand over the name; the browser adds the call when the event fires.
Side by side
button.addEventListener('click', showHours());button.addEventListener('click', showHours);Close cousins of this mix-up
The tutor watches for these in the same lesson.
“The listener needs the function with brackets.”
showHours() runs it now and passes along its result. Pass showHours with no brackets so it runs on the click.
“If the hours appear, the job is done.”
They appeared before anyone clicked. Something ran showHours while the page loaded.
“Switching to addEventListener is enough to fix it.”
The brackets are the bug, wherever they sit. Pass showHours, not showHours().
Practise it with a tutor watching
Events
Connect a click, a keystroke or a form to the function that should run.
Free, no account needed.