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 itselfCommon event types: click, input, submit, keydown, mouseover, focus, blur, change.
