Understand the idea
An event listener runs a function when an event occurs. Native buttons already support keyboard and pointer activation, so they are a good starting point for actions.
addEventListener takes an event name and a function to call later. Pass the function rather than calling it immediately. Use type="button" for a button that should not submit a surrounding form.
Read the example
This is a JavaScript fragment. Run it in a browser console or an external script. Supply any HTML or data file named in the example first.
// Add <button type="button" id="greet">Say hello</button> to the page.
// Run this script after that button exists.
const button = document.querySelector("#greet");
function greet() {
button.textContent = "Hello, web!";
}
if (button) {
button.addEventListener("click", greet);
}A small mistake, explained
What goes wrong
Passing greet() executes the function immediately instead of registering it to run on a later click.
How to fix it. Pass greet as a function reference, or wrap the call in an arrow function.
Try it yourself
Activate the button using the keyboard. Compare passing greet with passing () => greet(). Both register work for a future click; passing greet() calls the function immediately.
Further reading
DOM Standard — addEventListener
Keep exploring
- JavaScript · Guide
Variables & valuesGive a value a name and understand when it can change.
- JavaScript · Guide
Conditions & comparisonsMake a decision without accidentally changing the value.