addEventListener basics
Learn to add an event listener with addEventListener and how it differs from onclick.
Adding an event listener
To react to an element's events in JavaScript, you use the addEventListener method. It takes an event type (for example 'click') and a listener function; when the event fires, the function runs.
const button = document.querySelector('button');
button.addEventListener('click', () => {
console.log('Clicked');
});Older browsers used an onclick property on the element; but that approach allows only one listener. With addEventListener you can attach as many listeners as you want, and they all run without overwriting each other.
The listener function
The second parameter to addEventListener is a callback function. This function is called when the event fires. You can define the function separately and pass it by name, or write an arrow function inline.
function handleClick() {
console.log('Clicked');
}
button.addEventListener('click', handleClick);When you pass a function by name, do not use parentheses; writing handleClick() calls the function right away instead of waiting for the event. Passing by name is useful when you later want to remove the listener.
Exercise Write a click listener for the button
Select the button element with document.querySelector('button'). Add an arrow function handler to the 'click' event using addEventListener, and call console.log with a short message inside the handler.
Show example solution
const button = document.querySelector('button');
button.addEventListener('click', () => {
console.log('Clicked');
});
Test yourself
-
Which is the correct addEventListener syntax?
// A button.addEventListener(click, handler); // B button.addEvent('click', handler); // C button.addEventListener('click', handler); // D button.listen('click', handler);- A
- B
- C
- D
Show answer
C — Correct! The first parameter is the event type string, the second is the listener function.
-
Complete the click listener
const button = document.querySelector('button'); button.addEventListener(____, handleClick);Show answer
const button = document.querySelector('button'); button.addEventListener("click", handleClick); -
Match the concepts
- addEventListener
- Adds event listener
- onclick
- Sets one listener
- callback
- Runs on event
- 'click'
- Event type string