JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 12: Events and InteractionLesson 60 of 150About 50 minutes

Lesson 60: Building interactive components

01Opening question

Tabs, accordions and counters are all over the web. How do you build one that is reusable, keyboard friendly and easy to reason about?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

A component is a function that takes a root element, keeps its own state, listens for events and updates its own part of the page.

function createCounter(root) {
  let count = 0;
  const output = root.querySelector("output");
  root.addEventListener("click", (event) => {
    const action = event.target.closest("[data-action]")?.dataset.action;
    if (action === "inc") count++;
    if (action === "dec") count--;
    output.textContent = count;
  });
  return { get value() { return count; } };
}
const counter = createCounter(document.querySelector("#c"));
document.querySelector('[data-action="inc"]').click();
console.log(counter.value);

03Objective and prerequisites

Learning objective: Build small interactive components that keep their state in variables, update the DOM from that state, and expose correct ARIA attributes.

You need: Lesson 59: Event delegation, Lesson 55: Updating styles, attributes and classes

Skills practised: Events, Interactive components.

04Explanation

An interactive component is a piece of interface with its own behaviour: a tab bar, an accordion, a counter, a star rating.

Keep the component's state in variables (let open = false, let active = 0). Events change the state; a render function makes the page match it.

Wrap the component in a function that receives its root element. Calling the function twice gives two independent components with separate state (closures from Lesson 48).

Update ARIA attributes along with the visuals: aria-expanded for things that open, aria-selected for tabs, so screen reader users get the same information.

05Definitions

Component
A reusable piece of interface with its own markup, state and behaviour.
Component state
The values a component keeps, such as which tab is active, that decide what it shows.
render function
A function that updates the DOM so it matches the current state.
aria-expanded
An attribute telling assistive technology whether a control's related content is open.
CustomEvent
An event you create with your own name and a detail payload, dispatched like a built-in event.

Open the full glossary

06Visual learning object

Accessible interaction laboratory. Operate tabs and an accordion with mouse and keyboard and watch the state, the ARIA attributes and the focus update together.

Loading the interactive object…

Open the full Accessible interaction laboratory page with its guided experiment.

07Examples

ex-060-01An accordion Browser page (sandboxed preview)

Each button toggles its panel and keeps aria-expanded in sync.

const accordion = document.querySelector(".accordion");
accordion.addEventListener("click", (event) => {
  const button = event.target.closest("button[aria-controls]");
  if (!button) return;
  const panel = document.getElementById(button.getAttribute("aria-controls"));
  const open = button.getAttribute("aria-expanded") === "true";
  button.setAttribute("aria-expanded", String(!open));
  panel.hidden = open;
});
const [shipping, returns] = accordion.querySelectorAll("button");
returns.click();
console.log(returns.getAttribute("aria-expanded"), document.getElementById("p2").hidden);
returns.click();
console.log(returns.getAttribute("aria-expanded"), document.getElementById("p2").hidden);
Sample input
None
Expected output
true false false true

Two headings; Returns opens and closes

Common mistake
Toggling the panel but forgetting aria-expanded, so screen readers announce the wrong state.
Try this
Make opening one panel close the others.
Source
examples/ex-060-01-accordion.js

ex-060-02Tabs driven by state Browser page (sandboxed preview)

State (active index) changes on click; render updates every tab and panel.

function createTabs(root) {
  const tabs = [...root.querySelectorAll('[role="tab"]')];
  const panels = [...root.querySelectorAll('[role="tabpanel"]')];
  let active = 0;
  function render() {
    tabs.forEach((tab, i) => tab.setAttribute("aria-selected", String(i === active)));
    panels.forEach((panel, i) => { panel.hidden = i !== active; });
  }
  root.addEventListener("click", (event) => {
    const tab = event.target.closest('[role="tab"]');
    if (!tab) return;
    active = tabs.indexOf(tab);
    render();
  });
  render();
  return { get active() { return active; } };
}
const tabs = createTabs(document.querySelector(".tabs"));
document.querySelectorAll('[role="tab"]')[1].click();
console.log(tabs.active, [...document.querySelectorAll('[role="tabpanel"]')].map((p) => p.hidden).join(" "));
Sample input
None
Expected output
1 true false
Common mistake
Updating only the clicked tab and leaving the previously selected one marked as selected.
Try this
Add ArrowRight and ArrowLeft support on the tab list.
Source
examples/ex-060-02-tabs.js

ex-060-03Two independent counters Browser page (sandboxed preview)

Each call creates separate state, and querying inside the root keeps them apart.

function createCounter(root) {
  let count = 0;
  const output = root.querySelector("output");
  root.querySelector("button").addEventListener("click", () => {
    count++;
    output.textContent = count;
  });
}
document.querySelectorAll(".counter").forEach(createCounter);
const [a, c] = document.querySelectorAll(".counter button");
a.click(); a.click(); c.click();
console.log([...document.querySelectorAll("output")].map((o) => o.textContent).join(" / "));
Sample input
None
Expected output
2 / 1
Common mistake
Using document.querySelector("output") inside the component, so both counters update the first output.
Try this
Add a minus button to each counter.
Source
examples/ex-060-03-two-instances.js

ex-060-04Announcing changes with CustomEvent Browser page (sandboxed preview)

The component reports changes; the page decides what to do with them.

function createSwitch(input) {
  input.addEventListener("change", () => {
    input.dispatchEvent(new CustomEvent("toggle", { detail: { on: input.checked }, bubbles: true }));
  });
}
createSwitch(document.querySelector("#dark"));
document.addEventListener("toggle", (event) => {
  document.querySelector("#status").textContent = event.detail.on ? "Dark" : "Light";
  console.log("toggle", event.detail.on);
});
document.querySelector("#dark").click();
console.log(document.querySelector("#status").textContent);
Sample input
None
Expected output
toggle true Dark
Common mistake
Making the component change unrelated parts of the page directly, which ties it to one page.
Try this
Add a second listener that saves the choice in a variable.
Source
examples/ex-060-04-custom-event.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Keep components separate

Query inside the component's root.

function createLike(root) {
  let likes = 0;
  root.querySelector("button").addEventListener("click", () => {
    likes++;
    document.querySelector("span").textContent = likes;
  });
}
document.querySelectorAll(".like").forEach(createLike);
document.querySelector("#post-2 button").click();
console.log(document.querySelector("#post-1 span").textContent, document.querySelector("#post-2 span").textContent);

A disclosure widget

Keep state, visuals and ARIA in sync.

const button = document.querySelector("#more");
const details = document.querySelector("#details");
let open = false;
function render() {
  // TODO: details.hidden, aria-expanded and the button text
  // ("Show details" or "Hide details") must all follow open
}
button.addEventListener("click", () => {
  open = !open;
  render();
});
button.click();
console.log(details.hidden, button.getAttribute("aria-expanded"), button.textContent);

A quantity stepper component

Build a reusable component with limits and an API.

// Write createStepper(root): reads data-min and data-max, keeps value
// (starting at min), handles both buttons with one delegated listener,
// never goes outside min..max, updates the output, and returns
// { get value() { ... } }.

09Prediction

Commit to an answer first, then run the real code to compare.

// HTML: two <div class="t"><button>+</button></div>
let total = 0;
function make(root) {
  let n = 0;
  root.querySelector("button").addEventListener("click", () => { n++; total++; });
  return () => n;
}
const [a, b] = [...document.querySelectorAll(".t")].map(make);
document.querySelector(".t button").click();
console.log(a(), b(), total);

What is printed?

10Debugging investigation

Two tabs look selected at once

After clicking Week and then Month, both Week and Month are marked as selected.

const tablist = document.querySelector('[role="tablist"]');
let previous = tablist.children[0];
tablist.addEventListener("click", (event) => {
  const tab = event.target.closest('[role="tab"]');
  if (!tab) return;
  tab.setAttribute("aria-selected", "true");
  tablist.children[0].setAttribute("aria-selected", "false");
  previous = tab;
});
tablist.children[1].click();
tablist.children[2].click();
const state = () => [...tablist.children].map((t) => t.textContent + ":" + t.getAttribute("aria-selected")).join(" ");
console.log(state());

More cases in the Debugging Detective Laboratory

11Practical scenario

Design systems

Companies publish component libraries (buttons, tabs, dialogs) so every team builds the same accessible behaviour once. Each component takes a root element, keeps its own state, updates ARIA attributes, and emits custom events for the page to react to.

const components = ["tabs", "accordion", "dialog", "menu"];
console.log(components.map((c) => c + ": state + render + events").join("\n"));

12Knowledge check

1. Where should a component search for its own elements?

  • document
  • Inside its root element
  • window
  • The first match on the page

2. What does a render function do?

  • Fetches data
  • Updates the DOM so it matches the current state
  • Adds listeners
  • Creates state

3. Why do screen readers say the accordion is collapsed when it is open?

button.addEventListener("click", () => { panel.hidden = !panel.hidden; });
  • aria-expanded was not updated
  • hidden is wrong
  • The button needs an id
  • Accordions are not accessible

4. Two counters made by createCounter; the first is clicked twice. What are their values?

  • 2 and 2
  • 2 and 0
  • 1 and 1
  • 0 and 2

5. What does a CustomEvent's detail property hold?

  • The target element
  • Data the component wants to share with listeners
  • The event's phase
  • The default action

6. Which tab code is easier to keep correct?

  • Click handlers that change classes on clicked and previous tabs directly
  • A single active index plus a render that updates every tab from it
  • Separate listeners per tab that each update all tabs
  • Timers that check the active tab

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Keep components separate: Prints 0 1; Post 1 counts separately
  • A disclosure widget: Opens on click; Closes again
  • A quantity stepper component: Stops at the maximum; Stops at the minimum

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-12-events-and-interaction/lesson-060-building-interactive-components/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • Components keep state, listen for events and render their own markup.
  • Query inside the root so instances stay independent.
  • Keep ARIA attributes in step with what is shown.
  • Expose a small API and custom events instead of reaching into the page.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation interactive components
Context: I am learning interactive components in JavaScript.
Task: Explain how to build tabs and an accordion with state, render and accessible attributes.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction interactive components drill
Context: I have practised interactive components.
Task: Give me six component programs and ask what each instance shows after some clicks.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging interactive components bug
Context: My two counters on the same page update the same number.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation interactive components practice
Context: I finished the interactive components exercises.
Task: Create three component exercises with state, render and ARIA requirements.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review interactive components review
Context: Here is my code that uses interactive components.
Task: Review my component for global queries, missing ARIA updates and listeners that cannot be removed.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.