Event handling
Event handling is the practice of running your own code in response to something that happens on the page, such as a click, a key press, a form submission or a page finishing loading. The code you run is a function, often called a handler or listener, and you attach it to a specific element for a specific event type. Event handling is what turns a static page into an interactive one.
Three ways to attach a handler
JavaScript has grown three ways to connect a function to an event, and you will see all of them in real code:
- Inline HTML attribute:
<button onclick="save()">. Quick, but it mixes behaviour into markup and needs global functions. - DOM property:
button.onclick = save;. Simple, but each element can hold only one handler per event; assigning again replaces the first. addEventListener:button.addEventListener('click', save);. Allows several handlers for the same event, supports options, and can be removed cleanly. This is the recommended approach.
Using addEventListener
const likeButton = document.querySelector('#like');
let likes = 0;
function handleLike(event) {
likes += 1;
event.currentTarget.textContent = `Liked (${likes})`;
if (likes === 5) {
likeButton.removeEventListener('click', handleLike);
likeButton.disabled = true;
}
}
likeButton.addEventListener('click', handleLike);
// Runs once, then removes itself automatically
window.addEventListener('scroll', () => {
console.log('User started scrolling');
}, { once: true });
The first argument is the event name as a string without the "on" prefix. The second is the function to call. The optional third argument is an options object: once removes the listener after one call, passive promises the handler will not call preventDefault() and helps scrolling performance, and capture runs the handler during the capture phase.
The event object
The browser passes an event object to your handler. It describes what happened: event.type gives the event name, event.target is the element where it started, and event.currentTarget is the element the listener is attached to. Keyboard events add event.key, mouse events add coordinates such as event.clientX. The method event.preventDefault() stops the browser's built-in action, such as following a link or submitting a form.
Calling the function by accident
The most frequent beginner error is writing button.addEventListener('click', handleLike()). The parentheses call the function immediately while the listener is being added, and whatever it returns, usually undefined, becomes the "handler". Pass the function itself, without parentheses. If you need to pass arguments, wrap it: () => handleLike(postId).
That wrapper creates a new problem when removing listeners. removeEventListener only works when you pass the exact same function reference that was added. An anonymous arrow function cannot be removed later, so store the function in a variable if you plan to detach it, or use the once option or an AbortController signal.
Keeping handlers tidy
Keep handlers short and give them descriptive names such as handleLike. Move heavy work into separate functions, and avoid adding listeners inside loops when one listener on a parent element could handle all the children.
Takeaway
Use addEventListener with a function reference, read details from the event object, and keep a reference to any handler you intend to remove.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.