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);| Argument | What it means |
|---|---|
type | a string, the event name ('click', 'input', 'keydown', etc.) |
listener | the 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
| Method | What it does | Notes |
|---|---|---|
addEventListener() | Adds an event handler | You can attach several listeners to one event |
removeEventListener() | Removes a handler | Only works with the same function object |
options | Settings | { once, capture, passive } control the listener's behavior |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.