From Zero to Senior · The LabالعربيةGitHub

Chapter 16

Accessible Pages for Everyone

4 examples · 3 projects · 5 exercises

In this chapter you will learn to

  • explain what accessibility is and who it helps
  • use the right HTML element, the single most important accessibility skill
  • make pages that work with a keyboard, with visible focus and a skip link
  • write accessible forms, images and colours, and measure contrast yourself
  • check a page with the browser’s own tools

Examples

16.2 The right element for the job

Look at these two buttons:

buttons.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Accessible buttons</title>
    <style>
      body { font-family: system-ui, sans-serif; margin: 24px; }
      .fake, button { display: inline-block; padding: 10px 20px; border: 0; border-radius: 999px;
        color: white; background: #4338ca; font: inherit; cursor: pointer; margin: 4px; }
    </style>
  </head>
  <body>
    <h1>Two buttons</h1>
    <!-- Bad: looks like a button, but is only a box -->
    <div class="fake" onclick="alert('Hi')">I am a div</div>
    <!-- Good: a real button -->
    <button type="button" onclick="alert('Hi')">I am a button</button>
    <p>Both look the same. Only one works with a keyboard and a screen reader.</p>
  </body>
</html>
buttons.html560px
Figure 16.1: They look the same. They are not the same.

16.3 The keyboard test

Put your mouse away and try to use your page with the keyboard only. Tab moves forward through links, buttons and fields, Shift + Tab moves back, Enter follows links and presses buttons, and Space presses buttons and ticks boxes. Two things must be true:

focus.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Welcome</title>
    <style>
      body { font-family: system-ui, sans-serif; margin: 0; }
      .skip { position: absolute; inset-inline-start: 8px; top: -60px; padding: 8px 14px;
        background: #1e1b2e; color: white; border-radius: 8px; }
      .skip:focus { top: 8px; }
      nav { display: flex; gap: 8px; padding: 56px 16px 16px; background: #eef2ff; }
      nav a { padding: 6px 14px; border-radius: 8px; color: #312e81; font-weight: 700; }
      a:focus-visible { outline: 3px solid #db2777; outline-offset: 3px; }
      main { padding: 0 16px; }
      @media (prefers-reduced-motion: reduce) {
        * { animation: none !important; transition: none !important; }
      }
    </style>
  </head>
  <body>
    <a class="skip" href="#main">Skip to main content</a>
    <header>
      <nav aria-label="Main">
        <a href="#">Home</a>
        <a href="#">Projects</a>
        <a href="#">Contact</a>
      </nav>
    </header>
    <main id="main">
      <h1>Welcome</h1>
      <p>Press Tab to move between links. The focused link has a clear outline.</p>
    </main>
  </body>
</html>
focus.html560px
Figure 16.2: After pressing Tab once: the hidden skip link appears.
Figure 16.3: Two more presses: the focused link has a thick, clear outline.

16.5 Accessible forms

Do not start with “image of”; screen readers already say it is an image. Describe the purpose, not every pixel.

form.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Sign up</title>
    <style>
      body { font-family: system-ui, sans-serif; margin: 24px; max-width: 420px; }
      label { display: block; font-weight: 700; margin-top: 14px; }
      input { display: block; width: 100%; box-sizing: border-box; padding: 8px; font: inherit;
        border: 2px solid #5b5873; border-radius: 8px; }
      input[aria-invalid="true"] { border-color: #b91c1c; }
      .hint { color: #4a4760; margin: 4px 0 0; font-size: 0.9rem; }
      .error { color: #b91c1c; font-weight: 700; margin: 4px 0 0; }
      button { margin-top: 18px; padding: 10px 22px; border: 0; border-radius: 999px; color: white; background: #4338ca; font: inherit; }
    </style>
  </head>
  <body>
    <h1>Create an account</h1>
    <form novalidate>
      <label for="email">Email</label>
      <input id="email" type="email" autocomplete="email"
             aria-describedby="email-hint email-error" aria-invalid="true" value="sara@">
      <p class="hint" id="email-hint">We never share your email.</p>
      <p class="error" id="email-error" role="alert">Please enter a valid email address.</p>

      <label for="password">Password</label>
      <input id="password" type="password" autocomplete="new-password">

      <button type="submit">Create account</button>
    </form>
  </body>
</html>
form.html560px
Figure 16.4: A field with a hint and an error message that everyone can perceive.

16.6 Colour and contrast

WCAG asks for a contrast ratio of at least 4.5 to 1 between normal text and its background, and 3 to 1 for large text. The ratio goes from 1 (the same colour) to 21 (black on white). You saw DevTools show it in Chapter 6. Now, as a final JavaScript exercise, let us compute it ourselves with the official formula:

contrast.js⤓ File
// Contrast ratio between two colours, using the WCAG formula
function luminance(hex) {
  const channels = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255);
  const linear = channels.map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
  return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2];
}

function contrast(foreground, background) {
  const [a, b] = [luminance(foreground), luminance(background)].sort((x, y) => y - x);
  return (a + 0.05) / (b + 0.05);
}

const pairs = [
  ["#1e1b2e", "#ffffff"],
  ["#4338ca", "#ffffff"],
  ["#9ca3af", "#ffffff"],
  ["#ffffff", "#fbbf24"],
];

for (const [fg, bg] of pairs) {
  const ratio = contrast(fg, bg);
  const verdict = ratio >= 4.5 ? "pass" : "fail";
  console.log(`${fg} / ${bg}: ${ratio.toFixed(2)} → ${verdict}`);
}
Recorded output$ node contrast.js
#1e1b2e / #ffffff: 16.78 → pass
#4338ca / #ffffff: 7.90 → pass
#9ca3af / #ffffff: 2.54 → fail
#ffffff / #fbbf24: 1.67 → fail

Practice projects

Project 16.1 · Easy

Rescue a recipe card

This card looks fine, but a screen reader user, a keyboard user and someone in bright sunlight would all struggle with it. Find five problems and fix them.

You will practise: real buttons, headings and landmarks, alt text, labels, contrast, and the visible focus outline.

Steps
  1. The title is a div. Make it an h1, so it appears in the screen reader’s list of headings.
  2. The image has no alt. Describe what a sighted reader sees, in one short sentence.
  3. The search box has only a placeholder, which disappears as soon as you type. Give it a real <label>, and put it in a <form role="search">.
  4. “Search” and “Save recipe” are divs: Tab skips them. Turn them into <button> elements.
  5. The grey time text (#c4c4c4 on white) has a contrast of about 1.7. Darken it to #4b5563 and check the ratio with the script from section 16.6.
  6. Wrap the page in header, main and article, then do the keyboard test.

Hint: most accessibility fixes are not extra work. They are simply the right HTML element for the job, which you would have used anyway with a little more care.

Solution
recipe-before.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Recipe</title>
    <style>
      *, *::before, *::after { box-sizing: border-box; }
      body { margin: 0; padding: 24px; font-family: system-ui, "Segoe UI", Tahoma, sans-serif; background: #f5f5fb; color: #1e1b2e; line-height: 1.5; }
      h1 { color: #4338ca; margin-top: 0; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      :focus-visible { outline: 3px solid #db2777; outline-offset: 3px; }
      .card { max-width: 26em; background: white; border-radius: 16px; overflow: hidden; }
      .card img { width: 100%; display: block; }
      .body { padding: 16px; }
      .time { color: #c4c4c4; }
      .btn { display: inline-block; padding: 8px 18px; border-radius: 999px; color: white; background: #4338ca; }
    </style>
  </head>
  <body>
    <div class="title">Bit’s lentil soup</div>
    <input placeholder="Search recipes"> <div class="btn">Search</div>
    <div class="card">
      <img src="soup.svg">
      <div class="body">
        <div class="time">Ready in 30 minutes · Serves 4</div>
        <div class="btn" onclick="alert('Saved')">Save recipe</div>
      </div>
    </div>
  </body>
</html>
recipe-before.html640px
recipe.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Recipe</title>
    <style>
      *, *::before, *::after { box-sizing: border-box; }
      body { margin: 0; padding: 24px; font-family: system-ui, "Segoe UI", Tahoma, sans-serif; background: #f5f5fb; color: #1e1b2e; line-height: 1.5; }
      h1 { color: #4338ca; margin-top: 0; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      :focus-visible { outline: 3px solid #db2777; outline-offset: 3px; }
      .search { display: flex; gap: 8px; align-items: center; margin-bottom: 16px; flex-wrap: wrap; }
      .search input { font: inherit; padding: 7px 10px; border: 2px solid #6b7280; border-radius: 8px; }
      .card { max-width: 26em; background: white; border-radius: 16px; overflow: hidden; }
      .card img { width: 100%; display: block; }
      .body { padding: 16px; }
      .card h2 { margin: 0 0 4px; }
      .time { color: #4b5563; margin: 0 0 12px; }
      .secondary { background: #e0e7ff; color: #312e81; }
    </style>
  </head>
  <body>
    <header>
      <form class="search" role="search">
        <label for="q">Search recipes</label>
        <input id="q" type="search">
        <button type="submit">Search</button>
      </form>
    </header>
    <main>
      <h1>Bit’s lentil soup</h1>
      <article class="card">
        <img src="soup.svg" alt="A bowl of orange lentil soup with lemon on the side">
        <div class="body">
          <p class="time">Ready in 30 minutes · Serves 4</p>
          <button type="button">Save recipe</button>
          <button type="button" class="secondary">Print</button>
        </div>
      </article>
    </main>
  </body>
</html>
recipe.html560px
Project 16.1: the fixed card, with the keyboard focus on “Save recipe”.

Project 16.2 · Medium

A form that explains its errors

When the visitor makes a mistake, tell them what went wrong, where, and how to fix it, in a way that both eyes and screen readers notice.

You will practise: label, autocomplete, aria-describedby, aria-invalid, role="alert", and moving the focus with JavaScript.

Steps
  1. Build the form with a label for every field, and add novalidate so your script, not the browser, shows the messages.
  2. Under each input, add an empty <p class="error">, and link it to the input with aria-describedby. The screen reader will read it with the field.
  3. Keep the rules as data: an array of { id, message, ok }, where ok is a small function that tests the value.
  4. On submit, check every rule. Write the message, and set aria-invalid="true" on each field that fails.
  5. Fill a summary box at the top with a link to each problem, show it, and call summary.focus(). Because it has role="alert", it is announced at once.
  6. When everything is correct, hide the summary and show a success message in a role="status" element.

Hint: never use colour alone for errors. Here the message has words, the border changes, and the summary repeats it, so people who cannot see red still know what to do.

Solution
join.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Join the club</title>
    <style>
      *, *::before, *::after { box-sizing: border-box; }
      body { margin: 0; padding: 24px; font-family: system-ui, "Segoe UI", Tahoma, sans-serif; background: #f5f5fb; color: #1e1b2e; line-height: 1.5; }
      h1 { color: #4338ca; margin-top: 0; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      :focus-visible { outline: 3px solid #db2777; outline-offset: 3px; }
      form { max-width: 24em; display: flex; flex-direction: column; gap: 4px; }
      label { font-weight: 700; margin-top: 10px; }
      input { font: inherit; padding: 8px 10px; border: 2px solid #6b7280; border-radius: 8px; }
      input[aria-invalid="true"] { border-color: #b91c1c; }
      .hint { color: #4b5563; margin: 0; font-size: 0.9rem; }
      .error { color: #b91c1c; margin: 0; font-weight: 700; }
      .error:empty { display: none; }
      #summary { background: #fee2e2; border-inline-start: 5px solid #b91c1c; padding: 10px 14px; border-radius: 8px; max-width: 24em; }
      #summary[hidden] { display: none; }
      #summary ul { margin: 4px 0 0; }
      #summary a { color: #7f1d1d; }
      #done { color: #047857; font-weight: 700; }
      button { margin-top: 14px; align-self: flex-start; }
    </style>
  </head>
  <body>
    <h1>Join the coding club</h1>
    <div id="summary" role="alert" tabindex="-1" hidden></div>
    <form id="join" novalidate>
      <label for="name">Full name</label>
      <input id="name" autocomplete="name" aria-describedby="name-error">
      <p class="error" id="name-error"></p>

      <label for="email">Email</label>
      <input id="email" type="email" autocomplete="email" aria-describedby="email-hint email-error">
      <p class="hint" id="email-hint">We will only use it to send the meeting times.</p>
      <p class="error" id="email-error"></p>

      <button type="submit">Join</button>
    </form>
    <p id="done" role="status"></p>
    <script src="join.js"></script>
  </body>
</html>
join.html560px
Project 16.2: after submitting with an empty name and a broken email.
join.js⤓ File
const form = document.querySelector("#join");
const summary = document.querySelector("#summary");
const done = document.querySelector("#done");

const rules = [
  { id: "name", message: "Enter your full name.", ok: (value) => value.trim().length >= 2 },
  { id: "email", message: "Enter an email like name@example.com.", ok: (value) => /^\S+@\S+\.\S+$/.test(value) },
];

function showError(field, message) {
  const input = document.querySelector("#" + field);
  const error = document.querySelector("#" + field + "-error");
  error.textContent = message;
  input.setAttribute("aria-invalid", message ? "true" : "false");
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const problems = [];

  for (const rule of rules) {
    const value = document.querySelector("#" + rule.id).value;
    if (rule.ok(value)) {
      showError(rule.id, "");
    } else {
      showError(rule.id, rule.message);
      problems.push(rule);
    }
  }

  if (problems.length === 0) {
    summary.hidden = true;
    done.textContent = "Welcome to the club!";
    return;
  }

  const title = document.createElement("p");
  title.textContent = problems.length === 1 ? problems[0].message : "Please fix 2 problems:";
  const list = document.createElement("ul");
  for (const problem of problems) {
    const link = document.createElement("a");
    link.href = "#" + problem.id;
    link.textContent = problem.message;
    const item = document.createElement("li");
    item.append(link);
    list.append(item);
  }
  summary.replaceChildren(title);
  if (problems.length > 1) summary.append(list);
  summary.hidden = false;
  summary.focus();
});

Project 16.3 · Challenge

An accessible FAQ

Build questions that open and close their answers, and that tell assistive technology whether each one is open.

You will practise: buttons inside headings, aria-expanded, aria-controls, the hidden attribute, and querySelectorAll.

Steps
  1. For each question write an h2 containing a <button type="button" aria-expanded="false" aria-controls="answer-1">.
  2. Below it, put the answer in <div id="answer-1" hidden>. hidden hides it from everyone, screen readers included.
  3. Find all the buttons with querySelectorAll and give each a click listener.
  4. On click, read aria-expanded, flip it, and set the answer’s hidden to match.
  5. Draw the + and − with CSS from the attribute itself: button[aria-expanded="true"]::after. Now the look can never disagree with what the screen reader says.
  6. Test it with only the keyboard: Tab to a question, press Enter or Space, and Tab into the open answer.

Hint: because you used real buttons, Enter and Space work with no extra code. A div with a click listener would need a dozen lines to copy what <button> gives you free.

Solution
faq.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>FAQ</title>
    <style>
      *, *::before, *::after { box-sizing: border-box; }
      body { margin: 0; padding: 24px; font-family: system-ui, "Segoe UI", Tahoma, sans-serif; background: #f5f5fb; color: #1e1b2e; line-height: 1.5; }
      h1 { color: #4338ca; margin-top: 0; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      :focus-visible { outline: 3px solid #db2777; outline-offset: 3px; }
      .faq { max-width: 30em; }
      .faq h2 { margin: 0 0 8px; font-size: 1.05rem; }
      .faq h2 button { width: 100%; text-align: start; border-radius: 12px; padding: 12px 16px; display: flex; justify-content: space-between; gap: 12px; }
      .faq h2 button::after { content: "+"; font-weight: 700; }
      .faq h2 button[aria-expanded="true"]::after { content: "−"; }
      .answer { background: white; border-radius: 12px; padding: 4px 16px; margin: -4px 0 12px; }
    </style>
  </head>
  <body>
    <h1>Questions about the course</h1>
    <div class="faq">
      <h2>
        <button type="button" aria-expanded="false" aria-controls="answer-1">Do I need to install anything?</button>
      </h2>
      <div id="answer-1" class="answer" hidden>
        <p>Only a browser and VS Code. Both are free.</p>
      </div>
      <h2>
        <button type="button" aria-expanded="false" aria-controls="answer-2">How long does each chapter take?</button>
      </h2>
      <div id="answer-2" class="answer" hidden>
        <p>Most readers finish a chapter in two or three evenings, projects included.</p>
      </div>
      <h2>
        <button type="button" aria-expanded="false" aria-controls="answer-3">What if I get stuck?</button>
      </h2>
      <div id="answer-3" class="answer" hidden>
        <p>Re-read the hint, use the debugging method from chapter 14, then ask the community.</p>
      </div>
    </div>
    <script src="faq.js"></script>
  </body>
</html>
faq.html560px
Project 16.3: the FAQ with the second answer open.
faq.js⤓ File
const buttons = document.querySelectorAll(".faq button");

for (const button of buttons) {
  button.addEventListener("click", () => {
    const open = button.getAttribute("aria-expanded") === "true";
    const answer = document.querySelector("#" + button.getAttribute("aria-controls"));

    button.setAttribute("aria-expanded", String(!open));
    answer.hidden = open;
  });
}
+ 1 files
soup.svg⤓ File

Exercises

Exercise 16.1 · Easy

Use your profile page with the keyboard only. Can you reach every link? Can you always see where the focus is? Fix what you find.
The book's short answer
Typical fixes: replace clickable divs with buttons or links, and add a visible :focus-visible style.
Show the solution
profile.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="../../../ch07/examples/style.css">
    <link rel="stylesheet" href="keyboard.css">
    <title>About Sara</title>
  </head>
  <body>
    <header>
      <img src="../../../ch07/examples/bit.svg" alt="Sara’s avatar: a smiling purple robot" width="90" height="105">
      <h1>Sara Khan</h1>
      <p>Beginner web developer from Alexandria</p>
      <nav>
        <a href="#about">About</a> |
        <a href="#skills">Skills</a> |
        <a href="#contact">Contact</a>
      </nav>
    </header>

    <main>
      <section id="about">
        <h2>About me</h2>
        <p>I started learning to code this year with <em>Code from Zero</em>. I love building small tools that make life easier.</p>
      </section>

      <section id="skills">
        <h2>Skills I am learning</h2>
        <ul>
          <li>HTML</li>
          <li>CSS</li>
          <li>JavaScript</li>
        </ul>
      </section>

      <section id="contact">
        <h2>Contact</h2>
        <p>Write to me at <a href="mailto:sara@example.com">sara@example.com</a>.</p>
      </section>
    </main>

    <footer>
      <p>Built by Sara, with HTML and CSS.</p>
    </footer>
  </body>
</html>
profile.html640px
keyboard.css⤓ File
/* What the keyboard test found on the profile page from Chapter 7:
   1. Every link can be reached with Tab: they are real <a href> links, not clickable divs. Good.
   2. The focus is hard to see on the white menu buttons over the purple header, and on pink links in the cards.
   The fix: a thick outline that shows only for keyboard focus (:focus-visible), in a colour that stands out on both backgrounds. */
a:focus-visible,
button:focus-visible {
  outline: 3px solid #f59e0b;
  outline-offset: 3px;
  border-radius: 4px;
}

nav a:focus-visible {
  border-radius: 999px;
}

Exercise 16.2 · Easy

Add a skip link to your profile page.
The book's short answer
Copy the skip link and its CSS from focus.html, and add id="main" to <main>.
Show the solution
profile.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="../../../ch07/examples/style.css">
    <link rel="stylesheet" href="skip.css">
    <title>About Sara</title>
  </head>
  <body>
    <!-- The first thing Tab reaches: jumps over the header and menu to the content. -->
    <a class="skip" href="#main">Skip to main content</a>
    <header>
      <img src="../../../ch07/examples/bit.svg" alt="Sara’s avatar: a smiling purple robot" width="90" height="105">
      <h1>Sara Khan</h1>
      <p>Beginner web developer from Alexandria</p>
      <nav>
        <a href="#about">About</a> |
        <a href="#skills">Skills</a> |
        <a href="#contact">Contact</a>
      </nav>
    </header>

    <main id="main">
      <section id="about">
        <h2>About me</h2>
        <p>I started learning to code this year with <em>Code from Zero</em>. I love building small tools that make life easier.</p>
      </section>

      <section id="skills">
        <h2>Skills I am learning</h2>
        <ul>
          <li>HTML</li>
          <li>CSS</li>
          <li>JavaScript</li>
        </ul>
      </section>

      <section id="contact">
        <h2>Contact</h2>
        <p>Write to me at <a href="mailto:sara@example.com">sara@example.com</a>.</p>
      </section>
    </main>

    <footer>
      <p>Built by Sara, with HTML and CSS.</p>
    </footer>
  </body>
</html>
profile.html640px
skip.css⤓ File
/* From focus.html: hidden above the page until it gets the focus. */
.skip {
  position: absolute;
  inset-inline-start: 8px;
  top: -60px;
  padding: 8px 14px;
  background: #1e1b2e;
  color: white;
  border-radius: 8px;
  z-index: 10;
}

.skip:focus {
  top: 8px;
}

Exercise 16.3 · Medium

Run Lighthouse’s accessibility check on your profile page and on the shop from Chapter 13. Fix every problem it reports.
The book's short answer
Typical reports: missing alt, low contrast, missing labels, or a missing lang attribute.
Show the solution

Lighthouse is in Chrome's DevTools: open the page, press F12, choose the Lighthouse tab, tick Accessibility and click Analyze page load.

What it reported, and the fixes:

Page Problem Fix
Profile (ch. 7) Footer text #5b5873 on #f5f5fb: 6.3:1, passes. No other problems. —
Shop (ch. 13) Several "Add to cart" buttons with the same name; the total changes silently. aria-label with the product's name, aria-live on the total (see exercise 16.5).
recipe-before.html No alt, a field with no label, clickable divs, low contrast (#c4c4c4), no h1. Already fixed in the chapter's project recipe.html.

a11y-check.js finds the same kinds of problems automatically; run it with node a11y-check.js or give it your own pages.

a11y-check.js⤓ File
Runs with Node.js: node a11y-check.js
// A tiny automatic checker for the problems Lighthouse reports most often on beginners' pages.
// It reads the HTML as text, so it cannot replace Lighthouse (which checks the real page, colours included), but it finds the usual suspects in a second.
// Run: node a11y-check.js [file.html ...]
const fs = require("node:fs");
const path = require("node:path");

function check(file) {
  const page = fs.readFileSync(file, "utf8");
  const problems = [];

  if (!/<html[^>]*\slang="[^"]+"/.test(page)) problems.push("<html> has no lang attribute");
  if (!/<title>[^<]+<\/title>/.test(page)) problems.push("the page has no <title>");

  for (const img of page.match(/<img\b[^>]*>/g) || []) {
    if (!/\salt=/.test(img)) problems.push(`image without alt: ${img}`);
  }

  // Every input needs a <label for="its id"> (or an aria-label).
  const labels = new Set([...page.matchAll(/<label[^>]*\sfor="([^"]+)"/g)].map((m) => m[1]));
  for (const input of page.match(/<(input|textarea|select)\b[^>]*>/g) || []) {
    if (/type="(hidden|submit|button)"/.test(input) || /aria-label=/.test(input)) continue;
    const id = (input.match(/\sid="([^"]+)"/) || [])[1];
    if (!id || !labels.has(id)) problems.push(`field without a label: ${input}`);
  }

  // Clickable divs: the mouse can use them, the keyboard cannot.
  for (const div of page.match(/<div\b[^>]*onclick[^>]*>/g) || []) {
    problems.push(`clickable div instead of a button: ${div}`);
  }

  if (!/<h1\b/.test(page)) problems.push("no <h1> heading");
  if (!/<main\b/.test(page)) problems.push("no <main> landmark");

  return problems;
}

const here = (p) => path.join(__dirname, p);
const files = process.argv.length > 2 ? process.argv.slice(2) : [
  here("../../projects/recipe-before.html"),
  here("../../projects/recipe.html"),
  here("../../../ch07/examples/profile.html"),
  here("../../../ch13/examples/shop.html"),
];

for (const file of files) {
  const problems = check(file);
  console.log(`${path.relative(here("../.."), file)}: ${problems.length === 0 ? "no problems found" : problems.length + " problem(s)"}`);
  for (const p of problems) console.log(`  - ${p}`);
}
Recorded output$ node a11y-check.js
projects/recipe-before.html: 5 problem(s)
  - image without alt: <img src="soup.svg">
  - field without a label: <input placeholder="Search recipes">
  - clickable div instead of a button: <div class="btn" onclick="alert('Saved')">
  - no <h1> heading
  - no <main> landmark
projects/recipe.html: no problems found
../ch07/examples/profile.html: no problems found
../ch13/examples/shop.html: no problems found

Exercise 16.4 · Medium

Use contrast.js to check every text colour in your profile page’s stylesheet. Change any colour that fails.
The book's short answer
Run contrast(textColour, backgroundColour) for each pair; any result below 4.5 needs a darker text or a lighter background.
Show the solution
contrast-profile.js⤓ File
// contrast.js from the chapter, checking every text colour of the profile page's stylesheet (Chapter 7).
function luminance(hex) {
  const channels = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255);
  const linear = channels.map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
  return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2];
}

function contrast(foreground, background) {
  const [a, b] = [luminance(foreground), luminance(background)].sort((x, y) => y - x);
  return (a + 0.05) / (b + 0.05);
}

// [text, background, where]
const pairs = [
  ["#1e1b2e", "#f5f5fb", "body text"],
  ["#1e1b2e", "#ffffff", "text in the cards"],
  ["#ffffff", "#4338ca", "header text"],
  ["#4338ca", "#ffffff", "menu links, section titles"],
  ["#ffffff", "#db2777", "skill tags"],
  ["#db2777", "#ffffff", "links in the cards"],
  ["#5b5873", "#f5f5fb", "footer"],
];

let failures = 0;
for (const [fg, bg, where] of pairs) {
  const ratio = contrast(fg, bg);
  const verdict = ratio >= 4.5 ? "pass" : "fail";
  if (ratio < 4.5) failures++;
  console.log(`${fg} / ${bg}: ${ratio.toFixed(2)} → ${verdict}  (${where})`);
}
console.log(failures === 0 ? "Every pair passes 4.5:1. Nothing to change." : `Colours to change: ${failures}`);

// A colour that would fail, and a darker one that passes:
console.log(`#9ca3af / #ffffff: ${contrast("#9ca3af", "#ffffff").toFixed(2)}  →  #6b7280 / #ffffff: ${contrast("#6b7280", "#ffffff").toFixed(2)}`);
Recorded output$ node contrast-profile.js
#1e1b2e / #f5f5fb: 15.45 → pass  (body text)
#1e1b2e / #ffffff: 16.78 → pass  (text in the cards)
#ffffff / #4338ca: 7.90 → pass  (header text)
#4338ca / #ffffff: 7.90 → pass  (menu links, section titles)
#ffffff / #db2777: 4.60 → pass  (skill tags)
#db2777 / #ffffff: 4.60 → pass  (links in the cards)
#5b5873 / #f5f5fb: 6.26 → pass  (footer)
Every pair passes 4.5:1. Nothing to change.
#9ca3af / #ffffff: 2.54  →  #6b7280 / #ffffff: 4.83

Exercise 16.5 · Challenge

Turn on your computer’s or phone’s screen reader and try to buy a sticker in Bit’s shop without looking at the screen. Write down every moment you got lost, and fix the page.
The book's short answer
There is no single answer; common problems are buttons without names, images without alt, and changes that are not announced.
Show the solution

Screen readers: NVDA (free) or Narrator (Ctrl + Win + Enter) on Windows, VoiceOver (Cmd + F5) on a Mac or iPhone, TalkBack on Android.

Where I got lost trying to buy a sticker with my eyes closed, and the fix in this copy of the shop:

  1. Four buttons all called "Add to cart". Moving with Tab, I could not tell which one belonged to the sticker. Fix: aria-label="Add Bit sticker to cart" on each button.
  2. Nothing happened, as far as I could hear, after pressing the button: the total changed silently. Fix: aria-live="polite" on the total, so it is read out.
  3. The cards had no names, so "article" was all I heard. Fix: each card is labelled by its heading with aria-labelledby.
  4. The loading message already had role="status" in the chapter's version, so "Loading products…" was announced. Nothing to fix.
shop.html↗ Open page⤓ File
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bit’s Shop</title>
    <link rel="stylesheet" href="../../../ch13/examples/shop.css">
  </head>
  <body>
    <header><h1>Bit’s Shop</h1></header>
    <main>
      <section>
        <p id="status" role="status"></p>
        <div id="products"></div>
      </section>
      <aside id="cart">
        <h2>Your cart</h2>
        <ul id="cart-lines"></ul>
        <!-- aria-live: a screen reader announces the new total every time it changes. -->
        <p id="cart-total" aria-live="polite"></p>
      </aside>
    </main>
    <script src="shop.js"></script>
  </body>
</html>
shop.html640px
shop.js⤓ File
let catalog = [];

const cart = [];

// Draw one card per product
function renderProducts() {
  const container = document.querySelector("#products");
  for (const product of catalog) {
    const card = document.createElement("article");
    card.className = "card";

    // Each card is labelled by its heading, so a screen reader says which product it is in.
    card.setAttribute("aria-labelledby", `product-${product.id}`);

    const name = document.createElement("h3");
    name.id = `product-${product.id}`;
    name.textContent = product.name;

    const price = document.createElement("p");
    price.textContent = `$${product.price}`;

    const button = document.createElement("button");
    button.textContent = "Add to cart";
    // Four buttons called "Add to cart" sound the same; the label says which product.
    button.setAttribute("aria-label", `Add ${product.name} to cart`);
    button.addEventListener("click", () => addToCart(product.id));

    card.append(name, price, button);
    container.append(card);
  }
}

function addToCart(productId) {
  const line = cart.find((item) => item.productId === productId);
  if (line) {
    line.quantity++;
  } else {
    cart.push({ productId, quantity: 1 });
  }
  renderCart();
}

// Redraw the cart from the data every time it changes
function renderCart() {
  const list = document.querySelector("#cart-lines");
  list.replaceChildren();

  let total = 0;
  for (const item of cart) {
    const product = catalog.find((p) => p.id === item.productId);
    const lineTotal = product.price * item.quantity;
    total += lineTotal;

    const li = document.createElement("li");
    li.textContent = `${product.name} × ${item.quantity}`;
    const amount = document.createElement("span");
    amount.textContent = `$${lineTotal}`;
    li.append(amount);
    list.append(li);
  }

  document.querySelector("#cart-total").textContent =
    cart.length === 0 ? "Your cart is empty." : `Total: $${total}`;
}

// Load the products from the server, then draw the page
async function start() {
  const status = document.querySelector("#status");
  status.textContent = "Loading products…";
  try {
    const response = await fetch("../../../ch13/examples/products.json");
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    catalog = await response.json();
    status.textContent = "";
    renderProducts();
    renderCart();
  } catch (error) {
    status.textContent = "Sorry, the products could not be loaded. Please try again.";
    console.error(error);
  }
}

start();