Script Valley
JavaScript in the Browser: DOM, Events & APIs
Events and Event HandlingLesson 2.1

How addEventListener works in JavaScript

addEventListener syntax, event types, callback function, event object, removeEventListener, once option

addEventListener

addEventListener is the standard way to attach behaviour to user interactions. It takes an event type string, a callback, and an optional options object.

const btn = document.querySelector('#submit');

btn.addEventListener('click', function(event) {
  console.log('Clicked!', event);
});

// Arrow function โ€” same result
btn.addEventListener('click', (e) => console.log(e.type));

The Event Object

Every callback receives an Event object automatically. It carries information about what happened: e.type (event name), e.target (element that triggered it), and more depending on the event type.

Removing a Listener

To remove a listener, pass the exact same function reference to removeEventListener. An anonymous function cannot be removed โ€” store a reference when you need cleanup.

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

The once Option

btn.addEventListener('click', handleClick, { once: true });
// Fires once, then automatically removes itself

Common event types: click, input, submit, keydown, mouseover, focus, blur, change.

Up next

What is event bubbling and how does it work

Sign in to track progress

How addEventListener works in JavaScript โ€” Events and Event Handling โ€” JavaScript in the Browser: DOM, Events & APIs โ€” Script Valley โ€” Script Valley