Skip to content

Event Listeners

An event listener is a function that the browser calls when something happens to an element, such as a click, a key press or a change to a text field. Code attaches a listener with addEventListener(), which takes the event’s name and the function to call.

element.addEventListener('click', handleClick);

This is how most browser code runs. A page’s script sets up its listeners when it loads and then waits, and each user action triggers the function written for it. The browser examples on this page assume the script runs after the elements exist, for example from a <script> element at the end of the <body> or one with the defer attribute.

The browser passes the listener one argument, an event object that describes what happened. Its type property holds the event’s name, target is the element where the event started, and currentTarget is the element the listener is attached to.

<button id="add-item">Add to basket</button>
<p id="basket-count">Items in basket: 0</p>
const button = document.getElementById('add-item');
const count = document.getElementById('basket-count');
let items = 0;
button.addEventListener('click', (event) => {
items += 1;
count.textContent = `Items in basket: ${items}`;
console.log(event.type, event.target.id);
});

Each click adds one to the count shown in the paragraph and logs click add-item to the console. target and currentTarget are the same here, because the button has no child elements. They differ when an event starts on a child and is handled by a listener on its parent, which Event Bubbling & Propagation explains.

Pass the function itself, not the result of calling it. addEventListener('click', handleClick()) calls handleClick straight away and attaches whatever it returns.

A text field fires several events, and choosing the right one matters:

  • input fires on every change to the value, including each key press and each paste.
  • change fires when the user commits the value, which for a text field means leaving it after editing it.
  • focus and blur fire when the field gains and loses focus, whether or not the value changed.
<label>Book title <input id="title" type="text"></label>
<p id="preview"></p>
const field = document.getElementById('title');
const preview = document.getElementById('preview');
field.addEventListener('input', (event) => {
preview.textContent = `Preview: ${event.target.value}`;
});
field.addEventListener('change', (event) => {
console.log(`Saved title: ${event.target.value}`);
});

Typing updates the preview with every character, while the console logs the title only once, when the user tabs or clicks away from the field.

Some events have a default action, such as a link opening its address or a form sending its data and reloading the page. Calling event.preventDefault() cancels it, which lets the script handle the action itself. It is a method, so it needs the brackets, and writing event.preventDefault without them does nothing.

<form id="add-task">
<input name="task" placeholder="New task" required>
<button>Add</button>
</form>
<ul id="tasks"></ul>
const form = document.getElementById('add-task');
const list = document.getElementById('tasks');
form.addEventListener('submit', (event) => {
event.preventDefault();
const item = document.createElement('li');
item.textContent = form.elements.task.value;
list.append(item);
form.reset();
});

Submitting the form adds the task to the list and clears the field, and the page does not reload. Listening for submit on the form, rather than click on the button, also catches the user pressing Enter in the field.

removeEventListener() takes the same event name and the same function, so a listener that will be removed has to be a named function or one held in a variable. An options object as the third argument changes how a listener behaves, and { once: true } removes it automatically after its first call.

addEventListener() is not limited to the page, and Node.js has the same EventTarget class, so this example runs outside the browser:

const timer = new EventTarget();
const announce = (event) => console.log(`Heard "${event.type}"`);
timer.addEventListener('ring', announce);
timer.addEventListener('ring', () => console.log('First ring only'), { once: true });
timer.dispatchEvent(new Event('ring'));
timer.dispatchEvent(new Event('ring'));
timer.removeEventListener('ring', announce);
timer.dispatchEvent(new Event('ring'));
console.log('Done');

This prints:

Heard "ring"
First ring only
Heard "ring"
Done

The third event reaches no listener, because the first has been removed and the second ran once.

Older code sets a property such as button.onclick = handleClick instead. It still works, but an element can then have only one handler per event, and assigning a second replaces the first, whereas addEventListener() can attach as many as needed.

Steve Griffith covers this topic in his video Introduction to JavaScript Event Listeners.