Respond to an Event

Respond to an Event

An event listener registers work to perform when an event occurs. A school button can update an attendance count. Registering the listener alone changes nothing; a click invokes it.

Before this topic, review Remove Links Without Losing Their Text if its terms are unfamiliar.

What you’ll learn

  • Explain respond to an event through the school example.
  • Trace the shown operations and distinguish their result from displayed output.
  • Make the practice change and explain its consequence: The single handler invocation adds 1 to the new starting count.

Work through the school example

This is JavaScript in a browser. Read the initial values, then follow each operation to its displayed result. A declaration names a value, a function call performs an operation, and console.log displays its arguments.

Create this markup in a separate index.html, then place the JavaScript in a script after these elements. Use this isolated practice page so the selectors refer to its markup.

<button id="attend">Mark present</button>

JavaScript · browser · complete script for the supplied markup

let count = 0;
const button = document.querySelector("#attend");
button.addEventListener("click", () => {
  count++;
  console.log(count);
});
button.click();

Expected output

1

Event Handling in JavaScript

Events are the heartbeat of any interactive web application. Whether you're clicking a button, pressing a key, or submitting a form, events allow JavaScript to respond to user actions. This tutorial takes you from foundational event handling to advanced topics like event bubbling and delegation.

What is an Event?

An event is an action or occurrence that happens in the browser — like a user click, mouse movement, or a keystroke. JavaScript lets you listen to these events and react accordingly.

Basic Event Handling Using HTML Attributes

The simplest way to handle events is by adding event attributes directly in HTML.


<button onclick="alert('Button clicked!')">Click Me</button>

Event Handling with JavaScript (Recommended)

Using JavaScript to attach events is more flexible and maintainable.

const btn = document.querySelector("button");

btn.addEventListener("click", function () {
  alert("Button was clicked!");
});
(Button clicked, an alert appears)

Types of Common Events

  • click – when a user clicks an element
  • submit – when a form is submitted
  • keydown, keyup – when a key is pressed or released
  • mouseover, mouseout – when mouse hovers or leaves an element
  • change – when input value changes

Example: Handling a Form Submit Event


<form id="loginForm">
  <input type="text" id="username" placeholder="Username" required />
  <button type="submit">Login</button>
</form>
document.getElementById("loginForm").addEventListener("submit", function(e) {
  e.preventDefault();
  const user = document.getElementById("username").value;
  alert("Logged in as " + user);
});
Typed "john", clicked login => Alert: Logged in as john

Keyboard Events: keydown vs keyup


<input type="text" id="searchBox" placeholder="Type something..." />
<p id="log"></p>
const input = document.getElementById("searchBox");
const log = document.getElementById("log");

input.addEventListener("keydown", function(e) {
  log.textContent = "Key down: " + e.key;
});
Pressing "A" → Key down: a

Mouse Events Example


<div id="hoverBox" style="width:200px;height:100px;background:#ddd">
  Hover me!
</div>
<p id="status"></p>
const box = document.getElementById("hoverBox");
const status = document.getElementById("status");

box.addEventListener("mouseover", () => {
  status.textContent = "Mouse entered the box.";
});

box.addEventListener("mouseout", () => {
  status.textContent = "Mouse left the box.";
});
Mouse entered → "Mouse entered the box."
Mouse exited → "Mouse left the box."

Event Object and Its Properties

The event handler receives an event object which holds information like the target, key pressed, mouse position, etc.

document.addEventListener("click", function(e) {
  console.log("Clicked element:", e.target.tagName);
});
Clicked element: BUTTON

Event Bubbling vs Capturing

When you click a nested element, events bubble up from the target to the root. You can also capture events on the way down.


<div id="outer" style="padding:30px; background:lightblue;">
  Outer
  <div id="inner" style="padding:30px; background:lightgreen;">
    Inner
  </div>
</div>
document.getElementById("outer").addEventListener("click", () => {
  console.log("Outer div clicked");
});

document.getElementById("inner").addEventListener("click", () => {
  console.log("Inner div clicked");
});
Click inner → Logs: "Inner div clicked", then "Outer div clicked"

Event Delegation

Instead of adding event listeners to each child, you can attach one to the parent and use event.target to act conditionally.


<ul id="menu">
  <li>Home</li>
  <li>About</li>
  <li>Contact</li>
</ul>
document.getElementById("menu").addEventListener("click", function(e) {
  if (e.target.tagName === "LI") {
    alert("You clicked on " + e.target.textContent);
  }
});
Click "About" → Alert: You clicked on About

Removing Event Listeners

function greet() {
  alert("Hello!");
}

const btn = document.querySelector("button");
btn.addEventListener("click", greet);

// Later in the code
btn.removeEventListener("click", greet);

Custom Events

You can create your own events and dispatch them manually.

const msg = new CustomEvent("greet", {
  detail: { name: "Developer" }
});

document.addEventListener("greet", function(e) {
  console.log("Hello, " + e.detail.name + "!");
});

document.dispatchEvent(msg);
Hello, Developer!

Recognize the important boundary

This programmatic click demonstrates the handler; it is not a trusted physical user event. Remove unnecessary listeners when their owners are discarded.

Try a small variation

JavaScript · original source for practice

let count = 0;
const button = document.querySelector("#attend");
button.addEventListener("click", () => {
  count++;
  console.log(count);
});
button.click();

Your task: Replace count = 0 with count = 5. Predict the result before running the edited program.

The source is repeated here. If the edit targets the HTML rather than the script, use the markup repeated below; the worked answer also repeats the changed markup.

Markup used by this section:

<button id="attend">Mark present</button>

Worked answer and reasoning

The single handler invocation adds 1 to the new starting count.

Markup for this edited program:

<button id="attend">Mark present</button>

JavaScript · complete worked variation

let count = 5;
const button = document.querySelector("#attend");
button.addEventListener("click", () => {
  count++;
  console.log(count);
});
button.click();

Expected output

6

Predict the original program

JavaScript · original program for this question

let count = 0;
const button = document.querySelector("#attend");
button.addEventListener("click", () => {
  count++;
  console.log(count);
});
button.click();

Markup used by this section:

<button id="attend">Mark present</button>
In the browser, what does the original JavaScript example display, in order?
Choose one answer. You can try again.

Answer and explanation

1

An event listener registers work to perform when an event occurs. A school button can update an attendance count. Registering the listener alone changes nothing; a click invokes it. This programmatic click demonstrates the handler; it is not a trusted physical user event. Remove unnecessary listeners when their owners are discarded.

Keep the useful idea

An event listener registers work to perform when an event occurs. A school button can update an attendance count. Registering the listener alone changes nothing; a click invokes it.

Check your variation against this explanation: The single handler invocation adds 1 to the new starting count.

Use the JavaScript array reference library for individual array operations and boundary tests to check a rule independently.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Create and Insert an Element →