Handling Events in JavaScript
Responding to clicks, input, and other user interaction with addEventListener.
2 min read
An event is something that happens in the browser — a click, a keypress, a page finishing loading — that JavaScript can listen for and react to. addEventListener is the standard way to hook a function up to one.
The basic pattern
const button = document.querySelector("button");
button.addEventListener("click", () => {
console.log("Button was clicked!");
});The first argument names the event type ("click", "input", "submit", "keydown", and dozens more); the second is the function to run when it fires, called the handler or listener.
The event object
Every handler receives an event object describing what happened:
button.addEventListener("click", (event) => {
console.log(event.type); // "click"
console.log(event.target); // the exact element that was clicked
});event.target is especially useful when one listener covers multiple elements — it tells you exactly which one triggered the event, a pattern used heavily in event delegation, covered in the next lesson.
Common event types
input.addEventListener("input", e => console.log(e.target.value)); // fires on every keystroke
form.addEventListener("submit", e => {
e.preventDefault(); // stop the browser's default full-page reload
console.log("Form submitted");
});
document.addEventListener("keydown", e => console.log(e.key));
window.addEventListener("load", () => console.log("Page fully loaded"));preventDefault() is essential on form submission — without it, the browser does its native behavior (reloading the page and sending the form data as a full HTTP request) instead of letting your JavaScript handle it.
Removing a listener
function handleClick() {
console.log("Clicked");
}
button.addEventListener("click", handleClick);
button.removeEventListener("click", handleClick);removeEventListener requires a reference to the same function that was passed to addEventListener — an inline arrow function can never be removed this way, since a new function value is created every time.
Why not use onclick attributes
Older code sometimes uses <button onclick="doSomething()"> or button.onclick = fn. Both work, but only allow one handler per event per element — assigning a second onclick silently overwrites the first. addEventListener allows multiple independent listeners on the same event and element, and is the standard approach in modern code.
button.addEventListener("click", () => console.log("First"));
button.addEventListener("click", () => console.log("Second"));
// Both run on clickEvents don't just fire on the exact element clicked — they travel through the DOM tree. The next lesson covers exactly how, and why it matters.