SyntaxStudy
Sign Up
JavaScript Event Basics: addEventListener and removeEventListener
JavaScript Beginner 6 min read

Event Basics: addEventListener and removeEventListener

Event Basics

The DOM event system allows JavaScript to respond to user interactions and browser activities. At its core are two methods: addEventListener for registering handlers and removeEventListener for unregistering them.

addEventListener(type, handler, options)

Attach an event listener to any DOM element or the window object. The same element can have multiple listeners for the same event type, and they all fire independently. The optional third argument can be a boolean (useCapture) or an options object with once, capture, and passive properties.

removeEventListener(type, handler)

To remove a listener, you must pass the exact same function reference used when adding it. Anonymous inline functions cannot be removed this way, which is why named handler references are preferred when cleanup matters.

The Event Object

Every event handler receives an Event object containing information about the event: its type, the element it originated from (target), timestamps, and type-specific data.

Example
const btn = document.querySelector('#myButton');
function handleClick(event) {
  console.log('Clicked!', event.target);
  console.log('Event type:', event.type);
}
btn.addEventListener('click', handleClick);
btn.removeEventListener('click', handleClick);
btn.addEventListener('click', function() {
  console.log('Fires once');
}, { once: true });
window.addEventListener('resize', function() {
  console.log('Window width:', window.innerWidth);
});
Pro Tip

Use the { once: true } option instead of manually calling removeEventListener inside a handler — it is cleaner and eliminates the need to keep a reference to the function.