100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
JavaScript

Event Handling in JavaScript

Learn how to listen for and respond to user interactions and browser events using addEventListener and the event object.

DOM & EventsIntermediate10 min readJul 8, 2026
Analogies

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

javascript
// 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

html
<button id="btn">Save</button>
javascript
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

text
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

Was this page helpful?

Topics covered

#JavaScript#JavaScriptProgrammingStudyNotes#Programming#EventHandlingInJavaScript#Event#Handling#Syntax#Explanation#StudyNotes#SkillVeris