Skip to main content
← ⚑ JavaScript & the browserΒ·Module C2 Β· Lesson 3
TaskHTML has <button id='b'>click me</button>. Add a click listener that logs 'clicked!' to console every time the button is clicked.

addEventListener: click and the event object

75 XP7 min
Theory

The event-listener pattern

button.addEventListener("click", (event) => {
  console.log("clicked", event.target);
});

Three parts:

  1. The event name β€” "click", "input", "submit", "keydown", etc.
  2. The handler β€” your callback. Gets an event argument.
  3. event.target β€” the element that triggered the event. Useful in delegation (C2-08).

Why addEventListener beats onclick

button.onclick = first;
button.onclick = second;          // first is OVERWRITTEN

button.addEventListener("click", first);
button.addEventListener("click", second);   // BOTH run

onclick = clobbers any previous handler. addEventListener stacks. The latter is the only sane choice in any non-trivial codebase.

removeEventListener β€” pass the same function

const handler = () => { /* ... */ };
button.addEventListener("click", handler);
button.removeEventListener("click", handler);   // works

If you wrote addEventListener("click", () => { ... }) with an inline arrow, you CAN'T remove it later β€” there's no reference. Name your handler if you'll need to remove it.

πŸ”’

Sign up to start coding

Theory is open to everyone. The interactive editor, live preview, and check are unlocked with a 7-day free trial β€” card required, cancel anytime.

Sign up β€” free trial β†’

First 10 lessons in each track are free. No card needed for those.

← PreviousNext lesson β†’

Get one Python or web tip a day β€” by email

Short, hand-written, no spam. Unsubscribe in one click.