Clicking a button is the example everyone reaches for first, but JavaScript can react to a huge range of things happening on a page, and understanding events properly opens up a lot more than just "do something on click."

The pattern, one more time

element.addEventListener("eventType", function () {
  // what should happen
});

Events beyond click

  • "input" — fires as the user types into a text field, letter by letter.
  • "submit" — fires when a form is submitted, letting you intercept it before the page reloads.
  • "keydown" — fires when any key is pressed, useful for keyboard shortcuts.
  • "mouseover" and "mouseout" — fire when the mouse enters or leaves an element.
  • "load" — fires once the page has fully finished loading.

Stopping a form from reloading the page

const form = document.querySelector("form");
form.addEventListener("submit", function (event) {
  event.preventDefault();
  console.log("Form submitted, but the page didn't reload");
});

event.preventDefault() is one of those small lines that unlocks a lot. Without it, submitting a form does what forms have always done — sends the browser to a new page, which isn't what you want in most modern, JavaScript-driven forms.

The event object itself

button.addEventListener("click", function (event) {
  console.log(event.target);       // the exact element that was clicked
  console.log(event.type);         // "click"
});

Every event handler receives an event object describing what actually happened, which becomes essential once one function needs to handle clicks from several different buttons and figure out which one triggered it.

Event bubbling: events travel upward

Click a button inside a div, and technically the click event fires on the button first, then "bubbles" upward through every parent element containing it, all the way up to the whole document. This is why you can sometimes attach one listener to a parent element and catch clicks happening on any of its children, rather than attaching a separate listener to every single child individually — a pattern called event delegation, which is worth looking into once basic listeners feel comfortable.

Removing a listener

function handleClick() {
  console.log("clicked");
}
button.addEventListener("click", handleClick);
button.removeEventListener("click", handleClick);

Note this only works with a named function, not an anonymous one written directly inline — you need something to actually point back to when you want to remove it later.

The takeaway

Events are how a static page becomes an application that responds to a real person using it. Once addEventListener feels natural, most of what makes a website feel "interactive" rather than just "readable" starts to make a lot more sense.