Lesson 5 of 6 · 5 min

Events

Respond to clicks, typing and form submissions with addEventListener, use the event object, delegate events to a parent, and build a working theme toggle.

On this page
  1. addEventListener
  2. The event object
  3. Handling a form
  4. Live search
  5. Event delegation
  6. Removing listeners
  7. A complete theme toggle
  8. Try it

An event is something that happens on the page: a click, a key press, a form submission, the page finishing loading. You attach a function, called a listener or handler, that runs when it happens.

addEventListener

const button = document.querySelector("#theme-toggle")

button.addEventListener("click", () => {
  document.documentElement.classList.toggle("dark")
})

Common events:

Event When
click An element is clicked, tapped, or activated with Enter or Space (on buttons and links)
input The value of an input changes, on every keystroke
change An input's value is committed (a checkbox ticked, a select chosen)
submit A form is submitted
keydown A key is pressed
scroll The page or an element scrolls
DOMContentLoaded The HTML has been parsed

The event object

The listener receives an object describing what happened:

document.addEventListener("keydown", (event) => {
  if (event.key === "/" && document.activeElement === document.body) {
    event.preventDefault()               // don't type "/" anywhere
    document.querySelector("#search").focus()
  }
})
  • event.target is the element the event started on.
  • event.preventDefault() stops the browser's default action, such as following a link or submitting a form.

Handling a form

const form = document.querySelector("#signup")

form.addEventListener("submit", (event) => {
  event.preventDefault()                 // stay on the page
  const data = new FormData(form)
  const email = data.get("email")
  console.log("Signing up", email)
})

FormData reads every named field in the form. Object.fromEntries(new FormData(form)) turns it into a plain object.

const search = document.querySelector("#search")
const items = document.querySelectorAll(".lesson")

search.addEventListener("input", () => {
  const q = search.value.trim().toLowerCase()
  for (const item of items) {
    item.hidden = !item.textContent.toLowerCase().includes(q)
  }
})

Event delegation

Events bubble: a click on a button inside a list also fires on the list, then on the body, and so on up the tree. You can use that to handle clicks for many elements with one listener on their parent, including elements added later:

const list = document.querySelector("#lessons")

list.addEventListener("click", (event) => {
  const button = event.target.closest("button[data-lesson-id]")
  if (!button) return
  button.closest("li").classList.toggle("is-done")
})

Removing listeners

const onScroll = () => { /* ... */ }
window.addEventListener("scroll", onScroll, { passive: true })
window.removeEventListener("scroll", onScroll)

To remove a listener, you need the same function, so give it a name. { passive: true } promises you won't call preventDefault, which keeps scrolling smooth. { once: true } removes the listener automatically after it runs once.

A complete theme toggle

<button id="theme-toggle" type="button" aria-pressed="false">Dark mode</button>
const toggle = document.querySelector("#theme-toggle")
const root = document.documentElement

function setTheme(theme) {
  root.dataset.theme = theme
  toggle.setAttribute("aria-pressed", String(theme === "dark"))
  try { localStorage.setItem("theme", theme) } catch {}
}

setTheme(localStorage.getItem("theme") || "light")

toggle.addEventListener("click", () => {
  setTheme(root.dataset.theme === "dark" ? "light" : "dark")
})

Pair it with the CSS custom properties from the CSS course, and the whole page switches theme, and remembers the choice on the next visit.

Try it

Build a list of five lessons, each with a "Done" button. Use one delegated listener on the list to toggle a done class, and show a count of finished lessons that updates on every click.

More from JavaScript Crash Course