Listening to Events
Learn how to use addEventListener to respond to user actions like clicks and key presses, and how to change the DOM with event listeners.
Learn how to use addEventListener to respond to user actions like clicks and key presses, and how to change the DOM with event listeners.
Events are things that happen in the browser — a click, a key press, a form submission. addEventListener lets you run code when they occur.
element.addEventListener("event", callback);const button = document.querySelector("#my-button");
button.addEventListener("click", () => { console.log("clicked!");});Your callback receives an event object with details about what happened:
button.addEventListener("click", (event) => { console.log(event.target); // the element that was clicked console.log(event.type); // 'click'});For keyboard events, you get the key:
document.addEventListener("keydown", (event) => { console.log(event.key); // 'Enter', 'a', 'ArrowUp', etc.});| Event | When it fires |
|---|---|
click |
Mouse click or tap |
keydown |
Key pressed |
input |
Input value changes |
submit |
Form submitted |
mouseover |
Mouse enters element |
DOMContentLoaded |
HTML parsed, DOM ready |
const button = document.querySelector("#toggle");const box = document.querySelector("#box");
button.addEventListener("click", () => { box.classList.toggle("visible");});To remove a listener, you need a named function — arrow functions inline can’t be removed because you don’t have a reference:
function handleClick() { console.log("clicked");}
button.addEventListener("click", handleClick);button.removeEventListener("click", handleClick);Some events have default browser behavior. preventDefault() stops it:
form.addEventListener("submit", (event) => { event.preventDefault(); // stops page reload // handle submission manually});