The DOM & EventsCore· 40 min read

Events & addEventListener

React to clicks, typing, hovering and more — the proper, professional way to handle interaction.

What you will learn

  • Handle events with addEventListener
  • Respond to clicks and input
  • Read the event and the element

The professional way to handle events

Instead of inline onclick, attach handlers in JavaScript with addEventListener. It keeps HTML and behaviour separate and lets you add many handlers.

A click counter with addEventListener
<button id="btn">Click me</button>
<p id="count">Clicks: 0</p>

<script>
  let clicks = 0;
  const btn = document.getElementById("btn");
  btn.addEventListener("click", function() {
    clicks++;
    document.getElementById("count").textContent = "Clicks: " + clicks;
  });
</script>
Live preview

We keep a counter clicks starting at 0. btn.addEventListener("click", function(){...}) says "every time this button is clicked, run this function". Inside, clicks++ bumps the count by one and we rewrite the paragraph to show the new total. The function does not run now — it waits and fires on each click.

Note: Output: Starts at: Clicks: 0 After 3 clicks: Clicks: 3

Common events

EventFires when
clickAn element is clicked
inputA field’s value changes
submitA form is submitted
mouseover / mouseoutThe mouse enters / leaves
keydownA key is pressed

The input event fires on every keystroke, so we can react as the user types. Try typing your name in the box.

Live typing — the input event
<input id="name" placeholder="Type your name">
<p id="live">Hello, stranger!</p>

<script>
  document.getElementById("name").addEventListener("input", function(e) {
    document.getElementById("live").textContent = "Hello, " + (e.target.value || "stranger") + "!";
  });
</script>
Live preview

Each time you type, the handler runs. e.target is the input box itself, and e.target.value is whatever is currently typed in it. The || "stranger" part means "if the box is empty, use the word stranger instead". We drop that into the greeting, which updates instantly with every keystroke.

Note: Output: Empty box: Hello, stranger! Type "Asha": Hello, Asha!

Tip: Inside a handler, e.target is the element that fired the event, and e.target.value is what the user typed. This is the foundation of all interactive UIs — and React builds directly on it.

Q. Which method attaches an event handler the professional way?

Answer: addEventListener("click", fn) attaches a handler cleanly and supports multiple listeners per element.

✍️ Practice

  1. Build a click counter using addEventListener.
  2. Make a live character counter for a textarea using the input event.

🏠 Homework

  1. Build a button that toggles a “dark mode” class on the page when clicked.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →