Handling events
Overview
Events are how a page reacts to people. Clicking, typing, scrolling and submitting a form all fire events that your code can listen for.
const button = document.querySelector('#save');
button.addEventListener('click', () => {
console.log('Saved!');
});addEventListener takes the event type (a string) and a callback — the event handler or listener. You pass the function; the browser calls it every time the event happens.
Common events
| Event | Fires when… |
|---|---|
click |
an element is clicked (or activated with Enter/Space on a button) |
dblclick |
double-clicked |
input |
the value of a field changes, on every keystroke |
change |
a field’s value is committed (on blur, or when a checkbox/select changes) |
submit |
a form is submitted |
keydown / keyup |
a key is pressed / released |
focus / blur |
an element gains / loses focus |
mouseenter / mouseleave |
the pointer moves over / off an element |
scroll |
the page or an element scrolls |
DOMContentLoaded |
the HTML has been parsed |
load |
the page and all images have loaded |
The event object
Your callback receives an object describing what happened:
document.addEventListener('keydown', (event) => {
console.log(event.key);
});Useful properties:
button.addEventListener('click', (event) => {
event.type; // 'click'
event.target; // the element that was actually clicked
event.currentTarget; // the element this listener is attached to
event.clientX; // mouse position
event.shiftKey; // was Shift held?
});
input.addEventListener('keydown', (event) => {
if (event.key === 'Enter') submitSearch();
if (event.key === 'Escape') input.value = '';
if ((event.ctrlKey || event.metaKey) && event.key === 's') {
event.preventDefault(); // stop the browser's "Save page"
save();
}
});Stopping the default
Some events have a built-in action — a form submits and reloads the page, a link navigates. Call preventDefault() to handle it yourself:
form.addEventListener('submit', (event) => {
event.preventDefault();
// validate and send the data yourself
});Bubbling
When you click a button, the event doesn’t just fire on the button. It travels through the tree in three phases:
- Capture — from
documentdown towards the target. - Target — the element that was actually clicked.
- Bubble — back up through every ancestor to
document.
Listeners run in the bubble phase by default, so a click on a button also triggers click listeners on its parent <li>, the <ul>, and so on. (Pass { capture: true } to listen in the capture phase instead — rarely needed.)
event.stopPropagation() stops the event travelling further. Use it sparingly: other code — analytics, closing menus when you click elsewhere — often relies on bubbling.
Event delegation
Listening on many items? Add one listener to their parent and check
event.target. This is called event delegation.
const list = document.querySelector('.todo');
list.addEventListener('click', (event) => {
const button = event.target.closest('button.delete');
if (!button) return; // the click wasn't on a delete button
button.closest('li').remove();
});Delegation has two big advantages:
- One listener instead of hundreds — better for long lists.
- It works for items added later. New
<li>elements are handled automatically, because the listener is on the list, not the items.
Using closest rather than checking event.target directly matters: if the button contains an icon, the click’s target might be the icon, not the button.
Removing listeners
To remove a listener, pass the same function to removeEventListener — so it must be named, not an inline arrow:
function onScroll() { /* … */ }
window.addEventListener('scroll', onScroll);
window.removeEventListener('scroll', onScroll);Two handy options:
button.addEventListener('click', start, { once: true }); // removed after the first click
const controller = new AbortController();
window.addEventListener('resize', onResize, { signal: controller.signal });
window.addEventListener('scroll', onScroll, { signal: controller.signal });
controller.abort(); // removes both at oncethis in handlers
Inside a regular function handler, this is the element the listener is attached to (the same as event.currentTarget). Arrow functions don’t have their own this, so use event.currentTarget with them — it’s clearer anyway.
Performance tips
- Events like
scroll,resize,mousemoveandinputcan fire dozens of times a second. Keep their handlers light, or debounce them so work only happens once things settle — see Timers. - For scroll and touch listeners that never call
preventDefault, add{ passive: true }so the browser can scroll smoothly.
Accessibility
Use real <button> elements for things people click. A <div> with a click listener can’t be reached with the Tab key or activated with Enter, so keyboard and screen-reader users can’t use it. Buttons get all of that for free.
Count the clicks
Make the button show how many times it has been clicked. Then add a keyboard shortcut: pressing r resets the count to 0.
const button = document.querySelector('button');
let clicks = 0;const button = document.querySelector('button');
let clicks = 0;
function update() {
button.textContent = `Clicked ${clicks} times`;
}
button.addEventListener('click', () => {
clicks++;
update();
});
document.addEventListener('keydown', (event) => {
if (event.key === 'r') {
clicks = 0;
update();
}
});Summary
addEventListener(type, callback)runs your code when the event happens.- The callback receives an event object with details like
target,keyand the mouse position. - Call
event.preventDefault()to stop the browser’s default action. - Events bubble up from the target through its ancestors — so one listener on a parent can handle many children.
- Remove listeners with
removeEventListener(same function) or theonceandsignaloptions.