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
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.targetis 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.
Live search
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
- Lesson 1 · 5 minValues and variablesNumbers, strings, booleans, null and undefined, let and const, template literals, and why you should always compare with ===.
- Lesson 2 · 5 minFunctionsDeclare and call functions, parameters with defaults, return values, arrow functions, scope and closures, and passing functions as values.
- Lesson 3 · 5 minArrays and objectsStore lists and records, loop over them, transform them with map, filter, find and reduce, and copy them safely with spread and destructuring.