Skip to content

Intermediate · JavaScript in the browser: DOM and events · topic 36 of 64 · 30 min

Events: reacting to the user

Explanation

An event is a signal that something happened, such as a click, a key press or a form being sent. You attach a function with addEventListener, and the browser calls it with an event object that describes what happened. One listener on a parent can handle clicks on all its children (event delegation).

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).

Think of it like this: Think of a doorbell. You fit the bell once (addEventListener). Every time a visitor presses the button (the event), the bell rings (your function runs). You do not stand at the door all day checking for visitors.
javascript
const button = document.querySelector('#add-to-cart');
const count = document.querySelector('#cart-count');
let items = 0;

button.addEventListener('click', () => {
  items += 1;
  count.textContent = items;
});
addEventListener(eventName, function): run the function on every click

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.

EventWhen it firesCommon use
clickA mouse click or a tap on a phoneButtons, menus, cards
inputEvery time the value of a box changesLive search, character counter
changeWhen the user finishes changing a select, checkbox or boxFilters, dropdowns
submitWhen a form is sent (button or Enter key)Checking and sending forms
keydownWhen a key is pressed downShortcuts, Escape to close
javascript
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);
});
event.key gives the key name; event.target is the element

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.

javascript
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();
});
One listener on the list handles the remove button of every item

Removing a listener

javascript
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 });
To remove a listener you need the same named function
Tip: The option { passive: true } promises the browser that your scroll or touch listener will not call preventDefault. The browser can then scroll smoothly without waiting for your code, which helps on slow phones.
Careful: Avoid two old styles. Writing onclick="..." inside HTML mixes behaviour into the markup. event.keyCode is deprecated (no longer recommended). Use addEventListener and event.key.

Watch the lesson

Events: reacting to the user · 1/7

click, input, change, submit, keydown

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)

Task 1 · Code · Javascript

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.

Task 2 · Code · Javascript

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.

Task 3 · Practice

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

Question 1

1.What does button.addEventListener('click', showMenu) do?

Question 2

2.In modern code, which property tells you which key was pressed?

Question 3

3.A form reloads the page when submitted, but you want to check it with JavaScript first. What do you call in the submit listener?

Question 4

4.What is event delegation?

Question 5

5.Why does removeEventListener('click', () => go()) not remove your earlier listener?

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.

← Previous: The DOM and changing the page