Responding to User Actions
A page built only from HTML does not react to the user. JavaScript can react to it. Clicking a button, typing in a form, or hovering over an element can all run JavaScript code. We do that with event listeners.
Adding Event Listeners
The addEventListener method attaches a function to run when an event occurs:
const button = document.querySelector("#myButton");
button.addEventListener("click", () => {
console.log("Button was clicked!");
});
The first argument is the event type, and the second is the function to call (the event handler). The event handler runs each time the event occurs:
let clickCount = 0;
button.addEventListener("click", () => {
clickCount++;
console.log(`Clicked ${clickCount} times`);
});
Common Event Types
Here are the events you will use most often:
// Mouse events
element.addEventListener("click", handler); // Click
element.addEventListener("dblclick", handler); // Double click
element.addEventListener("mouseenter", handler); // Mouse enters element
element.addEventListener("mouseleave", handler); // Mouse leaves element
// Keyboard events (usually on document or inputs)
document.addEventListener("keydown", handler); // Key pressed
document.addEventListener("keyup", handler); // Key released
// Form events
input.addEventListener("input", handler); // Value changes
input.addEventListener("change", handler); // Value committed (blur or Enter)
input.addEventListener("focus", handler); // Element gains focus
input.addEventListener("blur", handler); // Element loses focus
form.addEventListener("submit", handler); // Form submitted
// Document events
document.addEventListener("DOMContentLoaded", handler); // DOM ready
window.addEventListener("load", handler); // Page fully loaded
The Event Object
Event handlers receive an event object with information about what happened:
button.addEventListener("click", (event) => {
console.log(event.type); // "click"
console.log(event.target); // The element that was clicked
});
Preventing Default Behavior
Some elements have built-in behaviors. Forms submit and reload the page, links navigate to URLs. Use preventDefault to stop these:
// Prevent form submission (handle with JavaScript instead)
form.addEventListener("submit", (event) => {
event.preventDefault();
const data = new FormData(form);
console.log("Handling form:", Object.fromEntries(data));
// Send data via fetch instead of traditional submit
});
// Prevent link navigation
link.addEventListener("click", (event) => {
event.preventDefault();
console.log("Link clicked, but not navigating");
});
We need this in single-page applications, where JavaScript handles navigation and form submission itself.
Removing Event Listeners
To remove a listener, you need a reference to the original handler function:
function handleClick() {
console.log("Clicked!");
}
button.addEventListener("click", handleClick);
button.removeEventListener("click", handleClick); // Works
// Anonymous functions can't be removed - no reference to pass
Advanced Event Topics
This chapter covers the basics of responding to events. The Event-Driven Programming chapter covers more advanced topics:
- Event propagation (bubbling and capturing)
- Event delegation for efficient handling
- Custom events for component communication
- The EventEmitter pattern in Node.js