In this video, you gave Priya’s page a Count me in button, handed the browser a function to call when it’s clicked, and watched the script finish before that function ever ran.
Key Points
- A
<button>is the HTML element for an action. A guest can click it, or reach it with the Tab key. - No line of your script can call a function at the moment a guest clicks, because the script can’t know when that will be. Instead, you hand the function to the browser.
- Every element has a method,
addEventListener(), that takes two arguments: the name of what to listen for, here the string"click", and the function to call. - A first attempt many people write is a detour:
countMeInButton.addEventListener("click", countMeIn());. The parentheses callcountMeIn()right there, while that line runs, so the Console showsCount me in clicked, thenmain.js finished, though nobody has clicked. Clicks then log nothing more, and there’s no error. - The call’s result,
undefined, is whataddEventListener()receives, so it has nothing to keep with the button. WithforEachGame(), this slip threw aTypeError. Here,addEventListener()kept nothing, so a click has no function to run, and the browser stays quiet. - Without the parentheses,
addEventListener("click", countMeIn)hands over the function itself. The script runs from top to bottom, the browser keepscountMeInwith the button, and nothing calls it. The script reaches its last line, logsmain.js finished, and finishes. - Each click then makes the browser call
countMeIn(), andCount me in clickedappears in the Console. Chrome stacks identical lines, so after three clicks you see one line with a 3 beside it. - The click is an event, something that happens on the page, and
countMeIn()is its handler, the function the browser calls for it. InaddEventListener(), listener means the same thing. - Watch out for the event’s name. It’s
"click", in lowercase, not"onclick", which names an HTML attribute, not an event. With"onclick"here, there’s no error, but no click ever calls your function. addEventListener()hands the browser your function, with no parentheses after its name. Your script runs to its end first. Then the browser calls the function, once for every click.
The Final Code
In scratch/index.html, the button sits in main, under the players list: