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.
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.
Search inside the root (root.querySelector), never the whole document, so two instances on one page do not interfere.
Handle the keyboard too: native <button> elements already respond to Enter and Space; tabs conventionally move with arrow keys and use roving tabindex.
Return a small public API (open(), close(), value) and an destroy() that removes listeners (an AbortController makes it one line), so other code can control the component.
Emitting a CustomEvent (root.dispatchEvent(new CustomEvent("tabchange", { detail, bubbles: true }))) lets the page react to the component without the component knowing about the page.
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.
Accessible interaction laboratory. Operate tabs and an accordion with mouse and keyboard and watch the state, the ARIA attributes and the focus update together.
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.
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?
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
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.
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 explanationinteractive 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 predictioninteractive 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.
Debugginginteractive 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 generationinteractive 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 reviewinteractive 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.