Reading history

JavaScript Events: addEventListener, Forms and Delegation

5 min read 1 views

Learn JavaScript events: addEventListener, the event object, click, input, submit and keydown, preventDefault and event delegation.

An event is something that happens on the page: a click, a key press, typing in a box, submitting a form or the page finishing loading. JavaScript can listen for an event and run a function when it occurs. Menus, sliders, live search boxes and browser games are all built on this idea, and addEventListener() is the method that wires an event to your code.

In this lesson you will learn

  • Attaching handlers with addEventListener()
  • Using the event object and event.target
  • Common events: click, input, submit, keydown
  • Stopping default behaviour with preventDefault()
  • Event delegation for lists that change

Click and Input Events

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Events</title>
  <style>
    body { font-family: sans-serif; }
    button { padding: 6px 14px; }
    #out { margin-top: 8px; color: #00695c; }
  </style>
</head>
<body>
  <button id="plus">+1</button>
  <button id="reset">Reset</button>
  <span id="count">0</span>
  <p><input id="name" placeholder="Type your name"></p>
  <p id="out">Waiting for input...</p>
  <script>
    let count = 0;
    const countEl = document.getElementById("count");

    document.getElementById("plus").addEventListener("click", () => {
      count++;
      countEl.textContent = count;
    });
    document.getElementById("reset").addEventListener("click", () => {
      count = 0;
      countEl.textContent = count;
    });

    document.getElementById("name").addEventListener("input", (event) => {
      const value = event.target.value.trim();
      document.getElementById("out").textContent =
        value ? "Hello, " + value + "! (" + value.length + " letters)" : "Waiting for input...";
    });
  </script>
</body>
</html>

Result

  • element.addEventListener("click", handler) runs handler every time the element is clicked. Try the buttons in the preview.
  • The handler receives an event object describing what happened. event.target is the element that triggered it, so event.target.value is the text in the input.
  • The input event fires on every change to a text field, which makes live previews and character counters simple. The change event fires only when the field loses focus.
  • The counter’s value lives in a variable, count; the page just displays it. Keeping data in variables and updating the DOM from them is a good habit.

Forms, preventDefault and Delegation

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Form and delegation</title>
  <style>
    body { font-family: sans-serif; }
    li { cursor: pointer; padding: 2px 0; }
    .error { color: crimson; }
  </style>
</head>
<body>
  <form id="todo-form">
    <input id="task" placeholder="New task">
    <button type="submit">Add</button>
    <span id="error" class="error"></span>
  </form>
  <ul id="tasks"><li>Click a task to remove it</li></ul>
  <script>
    const form = document.getElementById("todo-form");
    const input = document.getElementById("task");
    const tasks = document.getElementById("tasks");

    form.addEventListener("submit", (event) => {
      event.preventDefault();               // stop the page from reloading
      const text = input.value.trim();
      if (text === "") {
        document.getElementById("error").textContent = "Please type a task.";
        return;
      }
      document.getElementById("error").textContent = "";
      const li = document.createElement("li");
      li.textContent = text;
      tasks.appendChild(li);
      input.value = "";
      input.focus();
    });

    // One listener on the list handles every item, even new ones
    tasks.addEventListener("click", (event) => {
      if (event.target.tagName === "LI") event.target.remove();
    });
  </script>
</body>
</html>

Result

  • Listen for submit on the form, not click on the button. That way pressing Enter also works.
  • A form normally reloads the page when submitted. event.preventDefault() stops that so JavaScript can handle the data. It also stops links from navigating.
  • The code checks for an empty value and shows a message before adding anything. That is basic client-side validation.
  • Event delegation: instead of adding a listener to every <li>, one listener on the <ul> handles them all. Clicks bubble up from the clicked item to its parents, and event.target tells you which item was clicked. New items work automatically.

Common Events

EventFires when
click, dblclickAn element is clicked or double-clicked
inputThe value of a field changes, on each keystroke
changeA select, checkbox or field value is committed
submitA form is submitted
keydown, keyupA key is pressed or released; event.key says which
mouseenter, mouseleaveThe pointer moves onto or off an element
focus, blurAn element gains or loses focus
DOMContentLoadedThe HTML has been fully read (on document)

Common Mistakes

  1. Calling the handler instead of passing it: addEventListener("click", save()). Write save without parentheses.
  2. Forgetting preventDefault() on a form, so the page reloads and your changes vanish.
  3. Using inline onclick="..." attributes, which mix code into HTML and allow only one handler. Prefer addEventListener.
  4. Adding listeners inside a loop that runs repeatedly, so one click triggers the handler several times.

Practice Exercises

Exercise 1. Make a button with id theme toggle a dark class on the body.

Show answer
document.getElementById("theme").addEventListener("click", () => {
  document.body.classList.toggle("dark");
});

Exercise 2. Log the name of every key the user presses on the page.

Show answer
document.addEventListener("keydown", (event) => {
  console.log("Pressed:", event.key);
});

Frequently Asked Questions

How do I remove an event listener?

Call removeEventListener with the same event name and the same function reference. This only works if the handler was a named function or stored in a variable, not an inline arrow function.

What is the difference between event.target and event.currentTarget?

event.target is the element where the event started, such as the clicked list item. event.currentTarget is the element the listener is attached to, such as the list.

Summary

  • addEventListener(type, handler) runs code when something happens.
  • The event object describes the event; event.target is where it started.
  • Use submit with preventDefault() for forms.
  • Events bubble, so one listener on a parent can handle many children.

Next: JavaScript Strings.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *