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.

JavaScript · EXAMPLE
// 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

Original explanation and example prepared for HTML code FYI with AI assistance. Test the code in your own context. How these guides are made.