Intermediate · JavaScript in the browser: DOM and events · topic 36 of 64 · 30 min
Events: reacting to the user
Explanation
What is an event?
An event is a signal that something happened on the page: a click, a key press, text typed in a box, a form being sent. You tell the browser which function to run when an event happens. That function is called an event listener (or handler).
const button = document.querySelector('#add-to-cart');
const count = document.querySelector('#cart-count');
let items = 0;
button.addEventListener('click', () => {
items += 1;
count.textContent = items;
});The event object
The browser passes one argument to your function: the event object. It describes what happened. event.type is the name of the event, event.target is the element where it started, and event.key tells you which key was pressed.
| Event | When it fires | Common use |
|---|---|---|
| click | A mouse click or a tap on a phone | Buttons, menus, cards |
| input | Every time the value of a box changes | Live search, character counter |
| change | When the user finishes changing a select, checkbox or box | Filters, dropdowns |
| submit | When a form is sent (button or Enter key) | Checking and sending forms |
| keydown | When a key is pressed down | Shortcuts, Escape to close |
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
document.querySelector('#cart-drawer').hidden = true;
}
});
const search = document.querySelector('#search');
search.addEventListener('input', (event) => {
console.log('You typed:', event.target.value);
});Stopping the default action
Some events have a default action. Clicking a link opens a new page. Submitting a form reloads the page. event.preventDefault() stops that default, so your own JavaScript can handle it instead.
Bubbling and event delegation
When you click a button inside a list item inside a list, the click event fires first on the button, then on the li, then on the ul, and up to the document. This rising is called bubbling, like a bubble rising in water.
Event delegation uses bubbling. Instead of adding a listener to each of 100 items, add one listener to the parent. Inside it, use event.target.closest() to find which item was clicked. It even works for items you add later.
const cartList = document.querySelector('#cart');
cartList.addEventListener('click', (event) => {
const button = event.target.closest('button.remove');
if (!button) return; // the click was not on a remove button
const item = button.closest('li');
console.log('Removing', item.dataset.id);
item.remove();
});Removing a listener
function onScroll() {
console.log('Scrolled to', window.scrollY);
}
window.addEventListener('scroll', onScroll, { passive: true });
// later, when you do not need it:
window.removeEventListener('scroll', onScroll);
// run only once, then the browser removes it for you:
button.addEventListener('click', () => console.log('First click!'), { once: true });Watch the lesson
Events: reacting to the user · 1/7
Pages feel alive because they react to you. Every click, tap and key press is an event.
Prefer a video by a teacher? Find free videos on “javascript event listeners and event delegation tutorial” on YouTube ↗
In real life: A food delivery menu
A food delivery page shows 200 dishes, each with an "Add" button. Instead of 200 listeners, the developer puts one click listener on the menu list and uses event.target.closest('li') to find the dish and its data-id. An input listener on the search box filters dishes as you type, and a keydown listener closes the cart panel when you press Escape.
Practice (0/3 done)
A photo gallery uses the keyboard. Write a function handleKey(event) that returns "next" when event.key is "ArrowRight", "prev" when it is "ArrowLeft", "close" when it is "Escape", and null for any other key.
Event delegation: an order list has one click listener. Write a function getClickedId(event) that finds the <li> that was clicked with event.target.closest("li") and returns its dataset.id. If the click was not inside any <li> (closest returns null), return null.
Build a "shopping list" page in your browser. It has a text box, an Add button and a <ul>. Clicking Add (or pressing Enter in the box) adds the typed item as a new <li> with a small "Remove" button. Use one click listener on the <ul> (event delegation) to remove items. Press Escape to clear the text box.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.