Emmanuel Akinfulubi

JavaScriptEvents

Build an accessible toggle switch in JavaScript

Intermediate · 3 min read

Settings pages are full of switches: dark mode, notifications, autoplay. Each one is on or off, and one click flips it. It is easy to build something that looks like a switch. Building one that works for everyone, including people using a keyboard or a screen reader, takes a few more choices, and none of them are hard.

In this tutorial you will build a "Night mode" switch that flips between on and off when clicked, shows its state as text, and announces that state to screen readers. You should have used addEventListener and know that HTML attributes have values.

Start with a real button

You could draw a switch with a div and a click handler. But a div can't be reached with the Tab key, doesn't react to Space or Enter, and isn't announced as something you can press. You'd have to add all of that yourself.

A button already does all three. So the switch is a button:

index.html

<button id="sw" type="button" role="switch" aria-checked="false">
  Night mode <span id="state">off</span>
</button>

role and aria-checked

A screen reader is software that reads the page aloud. Two attributes tell it what this button is:

  • role="switch" says "this is an on/off switch", not an ordinary button.
  • aria-checked="true" or "false" says whether it is on right now.

The plan for this exercise is that aria-checked is the only place the state lives. The click handler reads it, flips it, and everything else follows from it.

Here is the exercise. Try it yourself first, or read on and we will build it.

7 A toggle switch

fair

Build a switch that flips between on and off when clicked. Make it a real control, not a styled div.

Stuck? Three hints, smallest first
  1. 1. Use a <button>. It is focusable and it responds to Space and Enter for free.
  2. 2. role="switch" with aria-checked is what makes the state announced.
  3. 3. Never keep the state only in a CSS class. Derive the class from the attribute.

Step 1: read the state

Step 1

const sw = document.getElementById('sw');
const on = sw.getAttribute('aria-checked') === 'true';
console.log(on); // false

getAttribute always gives back a string. So the comparison with 'true' turns it into a real true or false.

Here is the tempting shortcut, and why it fails:

JavaScript

console.log(Boolean('false')); // true
console.log(Boolean(''));      // false

Any string that isn't empty counts as true, including the word 'false'. So if (sw.getAttribute('aria-checked')) would think the switch is always on. Compare with === 'true' instead.

Step 2: flip it on click

Step 2

const sw = document.getElementById('sw');
const label = document.getElementById('state');
let toggles = 0;
sw.addEventListener('click', () => {
  const on = sw.getAttribute('aria-checked') === 'true';
  sw.setAttribute('aria-checked', String(!on));
  label.textContent = !on ? 'on' : 'off';
  toggles++;
});
sw.dispatchEvent(new Event('click'));
console.log(sw.getAttribute('aria-checked'), label.textContent); // true on
sw.dispatchEvent(new Event('click'));
console.log(sw.getAttribute('aria-checked'), label.textContent); // false off

Each click reads the current state, writes the opposite back with String(!on), and updates the visible word. !on ? 'on' : 'off' picks the word for the new state.

There's no separate let isOn variable. If there were, it could fall out of step with the attribute, and the switch would show one thing while announcing another. With one copy of the state, they always match.

Step 3: check it round-trips

Step 3

for (let i = 0; i < 4; i++) sw.dispatchEvent(new Event('click'));
console.log(sw.getAttribute('aria-checked'), toggles); // false 6

Four more clicks bring it back to off, and the counter shows six toggles in total.

Step 4: style it from the attribute

The look comes from CSS that reads the same attribute:

CSS

#sw {
  border: 1px solid #8e8e98;
  border-radius: 999px;
  padding: .4rem .9rem;
  background: #fff;
}
#sw[aria-checked="true"] {
  background: #17734b;
  color: #fff;
}
#sw:focus-visible {
  outline: 2px solid #3055d8;
  outline-offset: 2px;
}

#sw[aria-checked="true"] matches only while the switch is on, so the green color appears and disappears by itself. :focus-visible draws an outline when the switch is reached with the keyboard, so keyboard users can see where they are.

Because it is a real button, Tab reaches it and Space or Enter fires its click event. The same handler covers mouse and keyboard, with no extra code.

The full solution

The panel builds the switch and clicks it. Its checks confirm it starts off, each click flips the attribute and the label together, they never disagree, it is a real button with type="button" and role="switch", and four clicks bring it back to where it started. Press Run, then try the live demo with Tab and Space.

Live, in a real browser. Click it. Sandboxed to allow-scripts only, so it cannot reach this page.

The answer

const label = el('span', { id: 'state' }, 'off');
// A real button: focusable, and Space/Enter already fire click on it.
const sw = el('button', { id: 'sw', type: 'button', role: 'switch', 'aria-checked': 'false' }, ['Night mode ', label]);
document.body.appendChild(sw);

let toggles = 0;

sw.addEventListener('click', () => {
  // The attribute IS the state. Nothing else stores it, so nothing can disagree.
  const on = sw.getAttribute('aria-checked') === 'true';
  sw.setAttribute('aria-checked', String(!on));
  label.textContent = !on ? 'on' : 'off';
  toggles++;
});

const isOn = () => sw.getAttribute('aria-checked') === 'true';

console.log('at rest :', sw.getAttribute('aria-checked'), '| label', label.textContent);
fire(sw, 'click');
console.log('clicked :', sw.getAttribute('aria-checked'), '| label', label.textContent);
fire(sw, 'click');
console.log('again   :', sw.getAttribute('aria-checked'), '| label', label.textContent);
console.log('toggles :', toggles);

Output


      
14 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 14 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

14 checks

test('it starts off', isOn(), false);
test('and the attribute says so', sw.getAttribute('aria-checked'), 'false');
test('the visible label agrees', label.textContent, 'off');
test('clicking turns it on', (() => { fire(sw, 'click'); return isOn(); })(), true);
test('the label follows', label.textContent, 'on');
test('clicking again turns it off', (() => { fire(sw, 'click'); return isOn(); })(), false);
test('and the label follows back', label.textContent, 'off');
test('the announced state and the visible label never disagree', isOn() === (label.textContent === 'on'), true);
test('it is a real button, so a keyboard reaches it', sw.tagName, 'BUTTON');
test('with an explicit type so it cannot submit a form', sw.getAttribute('type'), 'button');
test('its role is announced as a switch', sw.getAttribute('role'), 'switch');
test('four clicks return it to the start', (() => { const before = isOn(); for (let i = 0; i < 4; i++) fire(sw, 'click'); return isOn() === before; })(), true);
test('and that is eight toggles in total', toggles, 8);
test('the state lives in exactly one place', sw.hasAttribute('aria-checked'), true);

Using a <button> rather than a <div> is most of the work. A button is already in the tab order, already responds to Space and Enter, and already announces itself as operable. A div with a click handler needs tabindex="0", a role, and its own keydown handler for Space and Enter, and it is still easy to get wrong.

role="switch" plus aria-checked is what makes the state audible. The important discipline is that aria-checked is the only copy of the state: the handler reads it, flips it, and the stylesheet colours the button from [aria-checked="true"]. Keep a separate boolean or a CSS class as well and you have two truths that will eventually disagree — the assertion checking the label and the attribute always match is guarding against precisely that.

Common mistakes

  • Using a div. It can't be focused or pressed with the keyboard. Start from a button.
  • Testing the attribute as a boolean. 'false' is a non-empty string, so it counts as true. Compare with === 'true'.
  • Keeping the state in two places. A separate variable or class can drift from aria-checked. Read and write the attribute only.

Try it yourself

  1. When the switch turns on, add a night class to document.body; when it turns off, remove it. Write CSS that darkens the page for body.night.
  2. Add a second switch, "Autoplay", using the same handler code for both. (Hint: use event.currentTarget instead of sw.)
  3. Save the state in localStorage and restore it when the page loads.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.