CodeMIRAI
0 XP

Events

2 min read 4 runnable examples Quiz included

Events are things that happen on a page: a click, a key press, a form being submitted, the mouse moving. You run code in response by attaching an event listener.

Listening for a click

HTML
<button id="btn">Click me</button>
<p id="out">Not clicked yet</p>

<script>
  const btn = document.querySelector("#btn");
  const out = document.querySelector("#out");
  let clicks = 0;

  btn.addEventListener("click", () => {
    clicks++;
    out.textContent = `Clicked ${clicks} time(s)`;
  });
</script>

addEventListener(type, handler) runs the handler function every time the event happens. Press Run, then click the button in the result.

Reacting to typing

The input event fires on every change to a text field:

HTML
<input id="name" placeholder="Type your name">
<h2 id="greeting">Hello, stranger</h2>

<script>
  const input = document.querySelector("#name");
  const greeting = document.querySelector("#greeting");

  input.addEventListener("input", () => {
    greeting.textContent = `Hello, ${input.value || "stranger"}`;
  });
</script>

The event object

The handler receives an event object with details about what happened:

HTML
<p>Press any key, then move the mouse over the box.</p>
<div id="box" style="width:240px;height:90px;background:#eef0ff;border-radius:10px"></div>
<p id="info"></p>

<script>
  const info = document.querySelector("#info");
  document.addEventListener("keydown", (e) => {
    info.textContent = `You pressed: ${e.key}`;
  });
  document.querySelector("#box").addEventListener("mousemove", (e) => {
    info.textContent = `Mouse at ${e.offsetX}, ${e.offsetY}`;
  });
</script>

Stopping the default action

Some events have a built-in behaviour. A form submission reloads the page; e.preventDefault() stops it so you can handle it yourself:

HTML
<form id="signup">
  <input name="email" type="email" placeholder="you@example.com" required>
  <button>Sign up</button>
</form>
<p id="msg"></p>

<script>
  document.querySelector("#signup").addEventListener("submit", (e) => {
    e.preventDefault();
    const email = e.target.email.value;
    document.querySelector("#msg").textContent = `Thanks! We'll write to ${email}.`;
  });
</script>

Common events

EventFires when
clickan element is clicked
inputa field's value changes
changea field's value is committed (e.g. a dropdown)
submita form is submitted
keydowna key is pressed
mouseover / mouseoutthe pointer enters / leaves
DOMContentLoadedthe HTML has finished loading
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.