Skip to main content

What do addEventListener() and removeEventListener() do?

addEventListener()

Purpose

Adds a handler (a function) that will be called when a specific event occurs.

Syntax:

javascript
element.addEventListener(type, listener, options);
ArgumentWhat it means
typea string, the event name ('click', 'input', 'keydown', etc.)
listenerthe function that runs when the event fires
options (optional)an object with additional settings (for example { once: true })

Example:

javascript
<button id="btn">Click me</button>
javascript
const btn = document.querySelector('#btn'); btn.addEventListener('click', () => { alert('Button clicked!'); });

Now this handler will be called on every click on the button.

Example with the event object:

javascript
btn.addEventListener('click', (event) => { console.log(event.type); // "click" console.log(event.target); // the element that was clicked });

Useful options:

javascript
btn.addEventListener('click', handler, { once: true, // the handler fires only once capture: false, // listen during the bubbling phase (default) passive: true, // tells the browser preventDefault will not be called });

removeEventListener()

Purpose

Removes a previously added event handler. Used when you need to turn off the reaction to an event.

Syntax:

javascript
element.removeEventListener(type, listener, options);

Important: To remove a handler, you must pass the same function you passed to addEventListener.

Incorrect:

javascript
btn.addEventListener('click', () => console.log('hi')); btn.removeEventListener('click', () => console.log('hi')); // will not work!

This creates two different anonymous functions, and the browser has no way to know which one to remove.

Correct:

javascript
function handleClick() { console.log('hi'); } btn.addEventListener('click', handleClick); btn.removeEventListener('click', handleClick);

Now the removal works.

A real-world example

javascript
function handleScroll() { console.log('Scrolling!'); } // Start listening window.addEventListener('scroll', handleScroll); // Stop listening after 3 seconds setTimeout(() => { window.removeEventListener('scroll', handleScroll); console.log('Listener removed!'); }, 3000);

Summary

MethodWhat it doesNotes
addEventListener()Adds an event handlerYou can attach several listeners to one event
removeEventListener()Removes a handlerOnly works with the same function object
optionsSettings{ once, capture, passive } control the listener's behavior

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.