1. Introduction
Events are signals fired by the browser when something happens: a click, a keystroke, a form submission, the page finishing loading, and many more. Event handling is the process of registering JavaScript functions ('event handlers' or 'listeners') that run in response to these signals, enabling interactive behavior.
Cricket analogy: A ball hitting the stumps, a boundary being signaled, or a review being called are all signals the ground broadcasts, and event handling is registering a scorer function that runs in response to each signal, enabling live, interactive scoring.
JavaScript provides multiple ways to attach handlers, but the modern, recommended approach is addEventListener, which is more flexible and powerful than legacy inline or property-based handlers.
Cricket analogy: A scoring app can attach handlers many ways, but the modern, recommended approach is addEventListener, similar to a stadium adopting a flexible digital signaling system over shouting instructions across the ground the old way.
2. Syntax
// addEventListener (recommended)
element.addEventListener('click', function handleClick(event) {
console.log('Clicked!', event.target);
}, { once: false, capture: false });
// Removing a listener (function reference must match)
element.removeEventListener('click', handleClick);
// Legacy alternatives
element.onclick = function (event) { console.log('onclick property'); };
// <button onclick="handleClick()">Click me</button> -- inline HTML attribute
// The event object
element.addEventListener('click', (event) => {
console.log(event.type); // 'click'
console.log(event.target); // element that triggered the event
console.log(event.currentTarget); // element the listener is attached to
});3. Explanation
addEventListener(type, handler, options) attaches a listener without overwriting any existing handlers on the same element — you can attach multiple listeners for the same event type. It also accepts an options object (capture, once, passive) for finer control, and listeners can be removed later with removeEventListener provided the exact same function reference is passed.
Cricket analogy: addEventListener('boundary', logFour, { once: true }) lets both the scorer and the commentary system react to the same boundary without overwriting each other, and removeEventListener can later drop the commentary handler if the exact same function reference is kept.
The onclick property-style handler (element.onclick = fn) can only hold one function at a time — assigning a new one overwrites the previous. Inline HTML attributes (<button onclick="...">) mix markup and behavior, are harder to maintain, and only support a single handler as well.
Cricket analogy: Setting scoreboard.onclick = showDetails and then later scoreboard.onclick = showReplay silently overwrites the first handler, just as an old-style inline <button onclick="..."> on a scorecard mixes markup and behavior and supports only one handler.
Inside a handler, the event object carries details about what happened: event.target is the actual element that triggered the event (e.g., the specific button clicked), while event.currentTarget is the element the listener is actually attached to (relevant when the listener is on an ancestor, due to event bubbling).
Cricket analogy: When a fan taps a specific fielder's icon on an interactive scorecard, event.target is that exact fielder, while event.currentTarget is the whole fielding-team panel the listener was attached to, since the click bubbled up from the fielder.
Gotcha: addEventListener lets you attach multiple independent listeners to the same element and event type, and none of them overwrite each other. Inline onclick / element.onclick can only ever hold a single handler — setting a new one silently replaces the old one, which is a common source of 'my handler stopped working' bugs.
4. Example
<button id="btn">Save</button>const btn = document.getElementById('btn');
function logClick(e) {
console.log('Listener A: clicked', e.target.id);
}
btn.addEventListener('click', logClick);
btn.addEventListener('click', (e) => {
console.log('Listener B: currentTarget is', e.currentTarget.id);
});
// This ALSO fires independently -- addEventListener does not overwrite
btn.onclick = () => console.log('onclick property handler');
// But this OVERWRITES the previous onclick handler
btn.onclick = () => console.log('second onclick handler (replaces first)');5. Output
After clicking the button once, console prints (order of registration):
Listener A: clicked btn
Listener B: currentTarget is btn
second onclick handler (replaces first)
Note: 'onclick property handler' never prints -- it was silently overwritten
by the second assignment to btn.onclick before any click occurred.6. Key Takeaways
- addEventListener supports multiple independent handlers per event type; onclick supports only one.
- event.target is the element that triggered the event; event.currentTarget is where the listener lives.
- removeEventListener requires the same function reference used in addEventListener.
- Options like { once: true } auto-remove a listener after it fires once.
- Prefer addEventListener over inline HTML attributes for maintainable, unobtrusive JavaScript.
Practice what you learned
1. What happens if you assign two different functions to element.onclick one after another?
2. How many listeners can be attached to the same element and event type using addEventListener?
3. Inside a click handler attached to a parent <div> that contains a clicked <button>, what does event.target refer to?
4. What is required to successfully call removeEventListener for a previously attached listener?
5. What does the { once: true } option do in addEventListener?
Was this page helpful?
You May Also Like
DOM Manipulation in JavaScript
Learn how to select, create, modify, and remove DOM elements using JavaScript, and the key differences between the main selector APIs.
Event Bubbling and Capturing in JavaScript
Understand the two phases of DOM event propagation — capturing (top-down) and bubbling (bottom-up) — and how to control them.
Form Validation in JavaScript
Learn to validate form input using built-in HTML5 constraint validation attributes and custom JavaScript logic.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics