Aral Code

The DOM Lesson 24 of 30

JavaScript Events and addEventListener

React to clicks, typing, mouse movement and key presses with addEventListener. Use the event object, preventDefault and event delegation.

An event is something that happens on the page: a click, a key press, a form being submitted, the mouse moving. JavaScript can listen for events and run a function when they happen. This is what makes pages interactive.

addEventListener

The modern way to handle events is addEventListener:

element.addEventListener("eventName", function () {
  // runs when the event happens
});
Example A click counter
<button id="btn">👍 Like</button>
<span id="count">0</span> likes
<script>
  let likes = 0;
  const btn = document.getElementById("btn");
  btn.addEventListener("click", () => {
    likes++;
    document.getElementById("count").textContent = likes;
  });
</script>

Compared with onclick="..." in the HTML, addEventListener keeps your JavaScript separate from your HTML, and lets you add more than one listener to the same element.

Common events

EventWhen it happens
clickThe element is clicked or tapped
inputThe value of an input changes (every keystroke)
changeA select, checkbox or input is changed and confirmed
submitA form is submitted
keydownA key is pressed
mouseover / mouseoutThe mouse enters / leaves
focus / blurAn input gets / loses focus
DOMContentLoadedThe HTML has finished loading

Live typing with the input event

Example A live character counter
<textarea id="msg" rows="3" cols="34" maxlength="140" placeholder="Write your status…"></textarea>
<p><span id="left">140</span> characters left</p>
<script>
  const msg = document.getElementById("msg");
  msg.addEventListener("input", () => {
    const left = 140 - msg.value.length;
    const out = document.getElementById("left");
    out.textContent = left;
    out.style.color = left < 20 ? "crimson" : "inherit";
  });
</script>

The event object

Your function receives an event object with details about what happened. It's usually named e or event:

Example Which key was pressed?
<input id="box" placeholder="Type here">
<p id="out"></p>
<script>
  document.getElementById("box").addEventListener("keydown", (e) => {
    document.getElementById("out").textContent =
      `You pressed: ${e.key}` + (e.key === "Enter" ? " ✅ (Enter detected!)" : "");
  });
</script>

Useful properties: e.target (the element the event happened on), e.key (for keyboard events), and e.clientX / e.clientY (mouse position).

preventDefault

Some events have a default action: a link opens a page, a form reloads the page when submitted. e.preventDefault() stops that, so your JavaScript can handle it instead:

Example Handling a form without reloading
<form id="f">
  <input id="n" placeholder="Your name" required>
  <button>Submit</button>
</form>
<p id="out"></p>
<script>
  document.getElementById("f").addEventListener("submit", (e) => {
    e.preventDefault();
    const name = document.getElementById("n").value.trim();
    document.getElementById("out").textContent = `Salamat, ${name}! Your form was received.`;
  });
</script>

Event delegation

If you have many buttons, especially ones that are added later, you don't need a listener on each. Put one listener on the parent and check e.target:

Example One listener for a whole list
<ul id="todo">
  <li>Assignment sa Math <button class="done">✔</button></li>
  <li>Review for quiz <button class="done">✔</button></li>
  <li>Linis ng kwarto <button class="done">✔</button></li>
</ul>
<script>
  document.getElementById("todo").addEventListener("click", (e) => {
    if (e.target.classList.contains("done")) {
      const li = e.target.closest("li");
      li.style.textDecoration = "line-through";
      li.style.opacity = "0.5";
    }
  });
</script>

This works because events bubble: a click on the button also travels up to the li, then the ul, and so on up to the document.

Removing a listener

To stop listening, use removeEventListener with the same function (it must be a named function, not an anonymous arrow). For listeners that should run only once, pass an option: btn.addEventListener("click", handler, { once: true }).

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. Which event fires on every keystroke in a text box?
2. What does e.preventDefault() do on a form's submit event?
3. What's wrong with btn.addEventListener("click", greet())?
4. What does e.target refer to?

By Sir Reyel · Last updated 2026-12-04