Popular Searches
Popular Course Categories
Popular Courses

Accessibility basics

Accessibility basics

29 mins HTML5 & Semantic Markup

Accessibility basics in React JS

Course: React JS Training

Topic: Accessibility basics

Course Link: React JS Training

Demo Link: Register for a Course Demo


1. Why accessibility matters in everyday web work

When we build a web page, we usually imagine a young user sitting at a laptop with a mouse and good eyesight. Real users are far more varied. Some cannot see the screen at all and listen to the page through a screen reader. Some cannot use a mouse and navigate only with the keyboard. Some have low vision, colour blindness, or difficulty reading long paragraphs. Others are only temporarily limited: a broken arm, a lost pair of glasses, a bright sunny screen on a commuter train, or holding a baby in one hand.

Accessibility is the practice of building pages that keep working in all of these situations. It matters for three practical reasons:

  • Reach: a page that a screen reader or a keyboard user cannot operate is a page that turns real visitors away.
  • Quality: accessible HTML tends to be cleaner HTML. Good headings, labels and structure also help search engines and make the code easier to maintain.
  • Responsibility: in many countries, websites used by the public are expected to meet accessibility standards, so this is a normal professional skill, not an optional extra.

For a React developer, this foundation is essential. React renders the interface, but the browser and assistive technologies still read the final HTML. If you understand accessible markup now, every component you write later will start from a solid base.

2. Accessibility in plain words

Accessibility means designing and coding a page so that everyone can perceive, understand, navigate and operate it, whatever their abilities, devices or situation.

Think of a shop entrance. A staircase serves many customers, but a ramp serves almost everyone, including a customer with a trolley or a wheelchair. Accessible HTML is that ramp. Adding a proper alt text, connecting a label to an input, or using a real button instead of a clickable div costs very little effort, yet it opens the same door for people who would otherwise be blocked.

Two ideas follow from this definition:

  • Accessibility is not a separate feature added at the end of a project. It is a way of writing markup from the first line.
  • Accessibility is not only about disability. Captions help people in noisy places, good contrast helps everyone on a phone in sunlight, and keyboard support helps power users.

3. Key terms you will meet

These words appear throughout this page and in every accessibility discussion, so learn them early:

TermMeaning in simple words
Assistive technologySoftware or hardware that helps people use a computer, such as screen readers, screen magnifiers, or switch devices.
Screen readerA program that reads the page aloud or shows it in braille, following the headings, labels and structure of the HTML.
Semantic HTMLUsing HTML elements for their real meaning, like nav, button and table, instead of generic div and span.
ARIAAccessible Rich Internet Applications: a set of HTML attributes that add extra role, state and label information for assistive technology.
WCAGThe Web Content Accessibility Guidelines, an international standard by the W3C that defines what "accessible" means, organised into levels A, AA and AAA.
Alt textText in the alt attribute of an image that describes the image for people who cannot see it.
FocusThe place on the page where keyboard actions will happen next, usually shown with a visible outline.
LandmarkA page region like header, nav, main or footer that screen reader users can jump to directly.
Contrast ratioThe measured difference in brightness between text colour and background colour, written like 4.5:1.

4. The four principles: perceivable, operable, understandable, robust

The WCAG standard groups every accessibility rule under four principles. Remember them by the letters POUR:

  • Perceivable: users must be able to sense the content with at least one of their senses. An image without alt text is invisible to a blind user, so it fails this principle.
  • Operable: users must be able to control the interface. A menu that only opens on mouse hover fails, because a keyboard user cannot reach it.
  • Understandable: content and behaviour must be predictable. A form that throws away everything when one field fails validation is hard to understand and use.
  • Robust: the page must work with current and future tools, including browsers and assistive technology. Clean, valid, semantic HTML is what makes this possible.

When you are unsure whether a design is accessible, test it against these four questions: Can everyone perceive it? Can everyone operate it? Does everyone understand it? Will it keep working as tools change?

5. Semantic HTML: your first accessibility tool

Before touching ARIA, remember that most accessibility comes free from choosing the right element. A screen reader does not read your CSS classes; it reads the element names. A div with a click handler is a mystery, while a button announces itself as a button, receives keyboard focus automatically, and responds to both <kbd>Enter</kbd> and <kbd>Space</kbd>.

Instead of this generic markupUse this semantic element
div with a click handlerbutton for actions, a href for navigation
div wrapping the top of the pageheader
div wrapping linksnav
div wrapping the main contentmain
span styled as a headingh1 to h6
div rows of datatable with th and caption
Text next to an inputlabel connected to the input

A short comparison shows the difference in practice:

<!-- Difficult for assistive technology to understand -->
<div class="top-bar">
  <div class="links">Shop &amp; Contact</div>
</div>
<div class="big-text">Welcome to our bakery</div>
<div class="clickable" onclick="order()">Order now</div>

<!-- Clear structure for everyone -->
<header>
  <nav aria-label="Main">
    <a href="/shop">Shop</a>
    <a href="/contact">Contact</a>
  </nav>
</header>
<main>
  <h1>Welcome to our bakery</h1>
  <button type="button">Order now</button>
</main>

In the second version, a screen reader user hears "header, navigation, main, heading level 1, button" and can jump straight to what they need. In the first version, they only hear unlabelled text with no map of the page.

6. Writing useful alternative text

The alt attribute is the most famous accessibility feature in HTML, and also the most misused. Good alt text is a short replacement for the image, not a file name and not a caption.

  • Describe the purpose, not the pixels. "Team celebrating after a product launch" is useful; "IMG_2045.jpg" and "photo" are not.
  • Keep it brief. One clear sentence is usually enough; screen reader users hear every word.
  • Do not start with "image of". The screen reader already announces that it is an image.
  • Mark decorative images with an empty alt. alt="" tells assistive technology to skip the image completely. This is a real decision, not an omission.
  • For images inside links, describe the destination. The alt text replaces the link text, so "Go to the checkout page" beats "shopping cart icon".
  • For charts and diagrams, provide the data nearby as text or a table, and keep the alt text short.
<!-- Informative image: describe what it shows -->
<img src="masala-dosa.jpg"
     alt="A golden crispy dosa served with coconut chutney and sambar">

<!-- Decorative image: screen readers skip it -->
<img src="swirl-divider.png" alt="">

<!-- Image used as a link: describe the destination -->
<a href="/checkout">
  <img src="cart.png" alt="Go to checkout">
</a>

A quick test: if you replaced the image with its alt text in a phone call, would the listener still understand the page? If not, rewrite it.

7. Accessible forms: labels, hints and grouping

Forms are where accessibility failures cost users the most, because a form is often the only way to sign up, buy or contact. Three habits cover most of the work:

  • Every input gets a real label connected with for matching the input's id. A placeholder disappears while typing and is not a label.
  • Related controls are grouped with fieldset and legend, so "Morning" is heard as "Delivery time, Morning" instead of a bare word.
  • Hints and error messages are linked with aria-describedby, so the screen reader reads them together with the field.
<form>
  <label for="email">Email address</label>
  <input type="email" id="email" name="email"
         autocomplete="email"
         aria-describedby="email-hint">
  <p id="email-hint">We use this only to send order updates.</p>

  <fieldset>
    <legend>Preferred delivery time</legend>
    <label><input type="radio" name="slot" value="morning"> Morning</label>
    <label><input type="radio" name="slot" value="evening"> Evening</label>
  </fieldset>

  <button type="submit">Place order</button>
</form>

Notice two extra details. autocomplete="email" lets browsers fill the field for users who find typing difficult. The submit button has real text, so it announces its purpose instead of just "button".

8. Keyboard access and visible focus

Many users move through a page with the <kbd>Tab</kbd> key, pressing <kbd>Enter</kbd> or <kbd>Space</kbd> to activate things. A page is keyboard accessible when:

  • Every interactive element can be reached in a sensible order, which native elements like a, button and input give you automatically.
  • The focused element is always clearly visible, so users never lose their place.
  • Nothing traps the keyboard, for example a popup that opens and then cannot be left with the <kbd>Esc</kbd> key or <kbd>Tab</kbd>.

Use tabindex sparingly and never with positive numbers:

  • tabindex="0" adds a custom element, such as a styled div acting as a widget, into the natural tab order.
  • tabindex="-1" allows an element to receive focus programmatically, for example moving focus to a dialog when it opens, without putting it in the tab order.
  • tabindex="1" or higher breaks the natural order and confuses keyboard users, so avoid it.

On long pages, offer a skip link so keyboard users can jump past the repeated navigation:

<body>
  <a href="#main-content" class="skip-link">Skip to main content</a>
  <header>...site navigation...</header>
  <main id="main-content">
    <h1>Course overview</h1>
  </main>
</body>

Never remove the focus outline without replacing it with something clearer:

/* Weak: focus disappears */
a:focus { outline: none; }

/* Better: a strong, visible focus style */
a:focus,
button:focus {
  outline: 3px solid #1a73e8;
  outline-offset: 2px;
}

9. ARIA: roles, states and properties

Semantic HTML covers most needs, but custom widgets go further. ARIA attributes fill that gap. They come in three kinds:

  • Roles declare what an element is: role="dialog", role="tab", role="alert".
  • States declare current conditions that change: aria-expanded, aria-checked, aria-disabled.
  • Properties declare relationships and labels that stay mostly stable: aria-label, aria-labelledby, aria-describedby, aria-controls.

The first rule of ARIA is important enough to memorise: prefer a native element over ARIA. A real button beats a div with role="button", because the native element also brings keyboard behaviour for free.

AttributeWhat it tells assistive technology
aria-labelA name for an element that has no visible text, such as an icon-only button.
aria-labelledbyPoints to the ID of another element that names this one.
aria-describedbyPoints to hint or error text that should be read after the element.
aria-expandedWhether a collapsible section, like a menu, is open (true) or closed (false).
aria-hidden="true"Hides decorative or duplicated content from assistive technology.
aria-current="page"Marks the current item in a navigation list.
aria-liveAnnounces updates that appear after load, such as form results.

A typical toggle button keeps its state in sync as the user clicks:

<button type="button"
        aria-expanded="false"
        aria-controls="filter-panel">
  Show filters
</button>

<div id="filter-panel" hidden>
  <!-- filter controls live here -->
</div>

When JavaScript opens the panel, it must also flip aria-expanded to true and remove the hidden attribute. The state attribute and the visible behaviour must always match, otherwise screen reader users hear the opposite of what sighted users see.

10. Landmarks and page structure

Screen reader users often do not read a page from top to bottom. They pull up a list of landmarks and headings, then jump. Semantic layout elements create that map:

<body>
  <header>
    <p>Street Bites Bakery</p>
  </header>

  <nav aria-label="Primary">
    <a href="/">Home</a>
    <a href="/menu">Menu</a>
  </nav>

  <main>
    <h1>This week's specials</h1>
    <article>
      <h2>Spinach paneer roll</h2>
      <p>Available from Monday to Friday.</p>
    </article>
    <aside aria-label="Related">
      <h2>Opening hours</h2>
    </aside>
  </main>

  <footer>
    <p>Street Bites Bakery</p>
  </footer>
</body>

Two rules keep this map clean:

  • Use exactly one main per page. It marks the content that is unique to this page, and it is also the natural target for a skip link.
  • Label repeated landmarks. If a page has two nav elements, give each an aria-label such as "Primary" and "Footer", so users can tell them apart.

Headings complete the structure. Keep the order logical, one h1 for the page topic, then h2 for sections and h3 inside them, and never choose a heading level for its font size, because CSS, not the level, controls appearance.

11. Making tables and media accessible

Data tables need explicit connections between headers and cells so a screen reader can say "Plan: Beginner, Classes per week: 2" instead of reading every cell as an isolated word:

<table>
  <caption>Weekly class schedule</caption>
  <thead>
    <tr>
      <th scope="col">Plan</th>
      <th scope="col">Classes per week</th>
      <th scope="col">Mode</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">Beginner</th>
      <td>2</td>
      <td>Online</td>
    </tr>
    <tr>
      <th scope="row">Advanced</th>
      <td>3</td>
      <td>Classroom</td>
    </tr>
  </tbody>
</table>

The caption gives the table a name, scope="col" marks column headers and scope="row" marks row headers. Use tables only for data; never use them to lay out a page, because the header-and-cell structure then becomes meaningless noise.

Multimedia needs alternatives for the senses it uses:

<video controls>
  <source src="lecture.mp4" type="video/mp4">
  <track src="lecture-en.vtt" kind="captions"
         srclang="en" label="English">
</video>
  • Videos get captions through a track kind="captions", so deaf users and people in noisy places can follow the speech.
  • Audio gets a transcript published as text next to the player.
  • Players must be keyboard operable, which is a reason to prefer the native controls attribute over fully custom play buttons until you can build them accessibly.
  • Nothing plays automatically with sound, because unexpected audio disorients screen reader users and everyone else.

12. Colour, contrast and readable text

Colour choices decide whether text is readable at all. Two rules from WCAG are worth knowing by heart:

  • Normal text needs a contrast ratio of at least 4.5:1 against its background.
  • Large text, roughly heading sizes, needs at least 3:1.

Light grey text on a white background is the most common failure you will see in student projects. Check your pairs with any contrast checker and adjust the colours, not the users' eyes.

The second rule is: never use colour as the only signal. A form that shows errors only by turning a border red fails for colour-blind users. Add a text message and, ideally, an icon:

<label for="phone">Phone number</label>
<input type="tel" id="phone" name="phone"
       aria-invalid="true"
       aria-describedby="phone-error">
<p id="phone-error">
  <strong>Error:</strong> Enter a 10-digit phone number.
</p>

Finally, let the page survive user preferences. Use relative units like rem for font sizes so text scales when users enlarge it, keep spacing flexible, and make sure the layout still works when the browser zooms in, because many low-vision users browse the whole web zoomed.

13. Step-by-step: checking a page for accessibility

Accessibility becomes manageable when you treat it as a routine checklist rather than a final exam. Work through a finished page in this order:

  1. Unplug the mouse. Move through the page using only <kbd>Tab</kbd>, <kbd>Shift</kbd>+<kbd>Tab</kbd>, <kbd>Enter</kbd>, <kbd>Space</kbd> and arrow keys. Can you reach and operate everything, in a sensible order, with focus always visible?
  2. Check the images. Every meaningful image has descriptive alt text; every decorative image has alt="".
  3. Check the headings. There is one h1, the levels descend without jumps, and reading only the headings out loud gives a sensible summary of the page.
  4. Check the forms. Every control has a real label, groups use fieldset and legend, and hints and errors are linked with aria-describedby.
  5. Check the landmarks. One main, labelled nav elements, and a skip link on long pages.
  6. Check colour and contrast. Text pairs meet the 4.5:1 or 3:1 ratios, and no information depends on colour alone.
  7. Check the media. Videos have captions, audio has transcripts, and nothing autoplays with sound.
  8. Check custom widgets. Every ARIA state, such as aria-expanded, updates together with the visible behaviour when JavaScript runs.

Run this list on every project you build in this course. The habit costs minutes while the page is small and saves painful rewrites later, and it is exactly the mindset you will need when you start building accessible React components on top of this HTML foundation.

14. Real-world pattern: navigation with a current-page marker

On a real site, the navigation bar repeats on every page, and one of its links points to the page you are already on. Screen reader users benefit from knowing which item is current, and sighted users usually get a highlighted style. The aria-current="page" attribute gives both groups the same information in one place:

<nav aria-label="Primary">
  <ul>
    <li><a href="/">Home</a></li>
    <li><a href="/courses" aria-current="page">Courses</a></li>
    <li><a href="/contact">Contact</a></li>
  </ul>
</nav>

A screen reader announces the second link as "Courses, current page" instead of just "Courses". You can then style it with an attribute selector instead of adding a special class:

nav a[aria-current="page"] {
  font-weight: bold;
  border-bottom: 3px solid #1a73e8;
}

Two habits make navigation robust: give every nav an aria-label when there is more than one on the page, and use lists for menu items so users hear how many links the menu contains.

15. Real-world pattern: accessible dialogs with the native dialog element

Custom popups are one of the hardest things to make accessible: you must move focus into the popup, trap <kbd>Tab</kbd> inside it while it is open, close it with <kbd>Esc</kbd>, and return focus to the trigger. The native dialog element does this work for you. When you open it with JavaScript's showModal() method, the browser handles focus placement and the <kbd>Esc</kbd> key automatically:

<button id="open-help" type="button">Help</button>

<dialog id="help-dialog" aria-labelledby="help-title">
  <h2 id="help-title">Need help with this form?</h2>
  <p>Check the hints under each field, or contact the support desk.</p>
  <button id="close-help" type="button">Close</button>
</dialog>

<script>
  const dialog = document.getElementById('help-dialog');
  document.getElementById('open-help').addEventListener('click', () => {
    dialog.showModal();
  });
  document.getElementById('close-help').addEventListener('click', () => {
    dialog.close();
  });
</script>

Notice the details that make it accessible: the dialog is labelled with aria-labelledby pointing at its heading, the trigger is a real button, and the dialog content starts with a heading so screen reader users hear what the popup is about. Whenever a native element can do the job, prefer it over a hand-built widget.

16. Announcing dynamic changes with live regions

When a page updates itself after loading — a search result count, a "saved" confirmation, a chat message — a sighted user sees the change, but a screen reader user hears nothing unless the update happens to have focus. Live regions solve this: an element marked as a live region announces changes to its text content even when the user is elsewhere on the page.

  • aria-live="polite" waits for a pause before announcing, right for status messages like "3 results found".
  • aria-live="assertive" interrupts immediately, right for urgent messages like a session expiring.
  • role="status" is a shorthand that implies polite live behaviour.
  • role="alert" is a shorthand that implies assertive behaviour.

The element must exist in the page before its text changes; adding the whole region at the same moment as the message is often too late for assistive technology to pick it up:

<p id="save-status" role="status"></p>
<button id="save" type="button">Save profile</button>

<script>
  document.getElementById('save').addEventListener('click', () => {
    // pretend we sent the data to a server here
    document.getElementById('save-status').textContent =
      'Your profile was saved.';
  });
</script>

When the button is clicked, the screen reader announces "Your profile was saved" without moving the user's focus. This small pattern removes one of the most common blind spots in dynamic interfaces.

17. Accessibility in your React workflow

Everything on this page applies directly to React, because assistive technology reads the final DOM that React renders, not your components. The habits simply move into JSX:

  • Use the same semantic elements (button, label, nav, main) inside components.
  • Write ARIA attributes as JSX props: aria-label, aria-expanded, aria-describedby keep their hyphenated names.
  • The for attribute becomes htmlFor in JSX, because for is a reserved word in JavaScript.
function CityField() {
  return (
    <>
      <label htmlFor="city">City</label>
      <input id="city" name="city" aria-describedby="city-hint" />
      <p id="city-hint">Used to match you with nearby batches.</p>
    </>
  );
}

State-driven attributes stay in sync automatically when you derive them from state, which is exactly what ARIA needs. A toggle button, for example, should never let the attribute and the visible behaviour disagree:

function Filters({ open, onToggle }) {
  return (
    <button
      type="button"
      aria-expanded={open}
      aria-controls="filter-panel"
      onClick={onToggle}
    >
      {open ? 'Hide filters' : 'Show filters'}
    </button>
  );
}

Because aria-expanded comes from the same state that changes the text, the announcement always matches what users see. As you move into server-side rendering later in the course, remember that pre-rendered HTML reaches the browser before JavaScript does, so semantic markup keeps the page usable even in that first moment.

18. Common mistakes and the correct way

Most accessibility failures in student projects come from a handful of repeating habits. Learn them now and you will avoid the bulk of real-world defects:

Common mistakeWhy it failsCorrect way
A div with a click handler used as a buttonNot focusable, not announced as a button, ignores <kbd>Space</kbd>Use <button type="button">
placeholder used as the only field labelDisappears on typing and is not a reliable labelUse a label connected with for and id
alt="image" or alt="photo.jpg"Says nothing the screen reader does not already announceDescribe the purpose: alt="Student working on a laptop"
outline: none on links and buttonsKeyboard users lose their place on the pageKeep a visible custom focus style
Positive tabindex valuesReorders the page and breaks expectationsUse natural order, or tabindex="0" only when needed
Errors shown only by red colourInvisible to colour-blind usersAdd text, aria-invalid and a linked message
Skipping heading levels, like h1 to h4The page outline becomes confusingDescend one level at a time; style with CSS
Icon-only links with no nameAnnounced as just "link"Add aria-label, for example aria-label="Open menu"
Auto-playing video or audioDrowns out screen reader speech and startles usersStart playback only on user action
Using table for page layoutHeader and cell announcements become meaninglessUse CSS layout; keep tables for data

19. Best practices for accessible markup

Condense everything from both parts of this page into habits you apply on every project:

  • Start with semantics. Choose the element whose meaning matches the content before reaching for ARIA or JavaScript.
  • Build for keyboard first. If you can operate the whole page with <kbd>Tab</kbd>, <kbd>Enter</kbd> and <kbd>Space</kbd>, most users are covered.
  • Name everything interactive. Buttons, links and inputs need accessible names, visible or provided with aria-label.
  • Keep state honest. Every ARIA state such as aria-expanded or aria-invalid must update together with the visible behaviour.
  • Announce what changes. Dynamic results and confirmations belong in a live region.
  • Separate structure from appearance. Headings for meaning, CSS for size; never pick a tag for how it looks.
  • Respect user settings. Use relative units like rem, support zoom, and avoid motion or sound the user did not ask for.
  • Test as you build. A two-minute keyboard pass on each new screen catches most problems early.

20. Practical project: an accessible course enquiry page

In this project you build a complete, working enquiry page that brings together landmarks, a skip link, labelled form fields, grouped choices, announced errors and a live status region. Build it in a single file called enquiry.html and follow the steps in order.

Step 1: create the page skeleton with landmarks

Set the language, the title, and the landmark structure, and add the skip link as the first element in the body:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Course enquiry - Web Foundations</title>
</head>
<body>
  <a href="#main-content" class="skip-link">Skip to main content</a>

  <header>
    <p>Web Foundations Programme</p>
  </header>

  <nav aria-label="Primary">
    <ul>
      <li><a href="/">Home</a></li>
      <li><a href="/enquiry" aria-current="page">Enquiry</a></li>
    </ul>
  </nav>

  <main id="main-content">
    <h1>Course enquiry</h1>
    <p>Fill in the form and we will get back to you.</p>
    <!-- the form from step 2 goes here -->
  </main>

  <footer>
    <p>Web Foundations Programme</p>
  </footer>
</body>
</html>

Step 2: build the form with labels, hints and grouping

Every control gets a label, every hint is linked with aria-describedby, and the radio choices are grouped with fieldset and legend. Error paragraphs are written in advance and hidden; the script in step 3 will reveal them:

<form id="enquiry-form" novalidate>
  <fieldset>
    <legend>Your details</legend>

    <label for="name">Full name</label>
    <input type="text" id="name" name="name" autocomplete="name" required>
    <p class="error" id="name-error" hidden>
      Please enter your full name.
    </p>

    <label for="email">Email address</label>
    <input type="email" id="email" name="email" autocomplete="email"
           required aria-describedby="email-hint email-error">
    <p id="email-hint">We reply to this address.</p>
    <p class="error" id="email-error" hidden>
      Please enter a valid email address.
    </p>
  </fieldset>

  <fieldset>
    <legend>Which course are you interested in?</legend>
    <label><input type="radio" name="course" value="web" required> Web Foundations</label>
    <label><input type="radio" name="course" value="react"> React JS Training</label>
  </fieldset>

  <label for="message">Your question</label>
  <textarea id="message" name="message" rows="4"></textarea>

  <button type="submit">Send enquiry</button>
  <p id="form-status" role="status"></p>
</form>

Step 3: add validation that announces itself

The script checks the fields, reveals the linked error messages, sets aria-invalid, moves focus to the first invalid field, and writes a summary into the live region so screen reader users hear the outcome:

<script>
  const form = document.getElementById('enquiry-form');
  const status = document.getElementById('form-status');

  function setError(input, errorId, hasError) {
    document.getElementById(errorId).hidden = !hasError;
    if (hasError) {
      input.setAttribute('aria-invalid', 'true');
    } else {
      input.removeAttribute('aria-invalid');
    }
  }

  form.addEventListener('submit', function (event) {
    event.preventDefault();

    const name = document.getElementById('name');
    const email = document.getElementById('email');
    let valid = true;

    if (name.value.trim() === '') {
      setError(name, 'name-error', true);
      valid = false;
    } else {
      setError(name, 'name-error', false);
    }

    if (email.value.includes('@') === false) {
      setError(email, 'email-error', true);
      valid = false;
    } else {
      setError(email, 'email-error', false);
    }

    if (valid) {
      status.textContent = 'Thank you! Your enquiry has been sent.';
      form.reset();
    } else {
      status.textContent =
        'The form has errors. Fix the highlighted fields and send it again.';
      const firstInvalid = form.querySelector('[aria-invalid]');
      if (firstInvalid) {
        firstInvalid.focus();
      }
    }
  });
</script>

Step 4: style focus and error visibility

The skip link stays hidden until it receives keyboard focus, and focus outlines are made strong rather than removed:

.skip-link {
  position: absolute;
  left: -9999px;
}

.skip-link:focus {
  left: 8px;
  top: 8px;
  background: #ffffff;
  padding: 8px 12px;
}

.error {
  color: #b00020;
  font-weight: bold;
}

a:focus,
button:focus,
input:focus,
textarea:focus {
  outline: 3px solid #1a73e8;
  outline-offset: 2px;
}

Step 5: test the finished page

  1. Open the page and press <kbd>Tab</kbd> from the address bar. The first stop should be the skip link; press <kbd>Enter</kbd> and confirm focus jumps to the main content.
  2. Tab through the whole form. Every field and button must show a clear focus outline, and the radio group must work with arrow keys.
  3. Submit the empty form. You should see both error messages, focus should land on the name field, and the status line should describe the problem.
  4. Fix the fields and submit again. The status line should change to the thank-you message.
  5. If a screen reader is available, repeat the pass and listen to how each field, hint and error is announced.

21. Practice Exercises

  • Take any page you built earlier in this module and run the full checklist from part 1 on it: fix every missing alt, every unlabelled input, and every heading-level jump you find.
  • Build an icon-only toolbar with three buttons that have no visible text, and give each one an aria-label. Verify with the keyboard that each is announced and focusable.
  • Convert a card whose whole area is a clickable div into a version where the title is a real link or the action is a real button, and test that <kbd>Enter</kbd> activates it.
  • Add aria-current="page" to a multi-page mini site you have, and style the current link with an attribute selector instead of a class.
  • Extend the enquiry project: validate the radio group too, and if nothing is selected, announce it in the status region and move focus to the first radio button.
  • Zoom your enquiry page to 200% in the browser and confirm that no content or form field becomes unusable, then resize the window to a narrow phone width and repeat.

22. Interview Questions and Answers

What is web accessibility and why should a developer care about it?

Accessibility is the practice of building pages that everyone can perceive, operate and understand, including people with visual, hearing, motor or cognitive limitations. Developers care because it widens the audience, improves overall markup quality, helps search engines understand the page, and is a professional expectation for public-facing websites.

What is the difference between semantic HTML and ARIA?

Semantic HTML uses elements whose meaning is built in, like button, nav and table, and assistive technology understands them automatically. ARIA is a set of attributes that adds role, state and label information when no native element fits. The first rule of ARIA is to prefer a native element, because it also brings keyboard behaviour for free; use ARIA to fill genuine gaps in custom widgets.

How do you write good alt text, and what about decorative images?

Good alt text briefly describes the purpose of the image in context, without starting with "image of" and without repeating file names. Images that carry no information, like decorative dividers, should use an empty alt="" so screen readers skip them entirely. Images used inside links should describe the destination, because the alt text replaces the link text.

Explain the values of the tabindex attribute.

tabindex="0" places a normally unfocusable element, such as a custom widget, into the natural tab order. tabindex="-1" lets an element receive focus programmatically, for example moving focus into a dialog when it opens, without adding it to the tab order. Positive values force a custom order, which breaks keyboard expectations, so they should not be used.

What is the difference between aria-label, aria-labelledby and aria-describedby?

aria-label gives an element a name directly as a string, useful for icon-only buttons. aria-labelledby points to the ID of another element whose visible text names this one. aria-describedby points to supplementary text, such as hints or error messages, that should be read after the element's name.

How does aria-expanded work in a collapsible menu?

The trigger button carries aria-expanded="false" while the panel is closed and aria-expanded="true" while it is open, often together with aria-controls pointing at the panel's ID. The critical rule is that JavaScript must update the attribute at the same moment as the visible change, so the announcement always matches what users see.

What are live regions and when do you use them?

A live region is an element whose text changes get announced without moving the user's focus. Use aria-live="polite" or role="status" for non-urgent updates like result counts and confirmations, and aria-live="assertive" or role="alert" for urgent messages. The region must exist in the DOM before its content changes, and it should not steal focus for ordinary status updates.

What does WCAG stand for and what are its four principles?

WCAG is the Web Content Accessibility Guidelines, the international standard that defines what accessible content means, organised into conformance levels. Its four principles are that content must be perceivable, operable, understandable and robust, often remembered as POUR. Almost every practical rule, from alt text to keyboard access, maps onto one of these four.

What contrast ratios should text meet?

Normal-sized text needs a contrast ratio of at least 4.5:1 against its background, and large text needs at least 3:1. Light grey text on white is the classic failure. Also, colour must never be the only way information is conveyed, so error states need text or icons in addition to red styling.

What is a skip link and why is it useful?

A skip link is the first focusable element on the page, usually written as <a href="#main-content">Skip to main content</a>, which lets keyboard users jump past the repeated navigation straight to the content. It is normally hidden off-screen and becomes visible when it receives focus, so it does not disturb the visual design.

How do you test a page for accessibility?

Start by unplugging the mouse: navigate with <kbd>Tab</kbd>, <kbd>Shift</kbd>+<kbd>Tab</kbd>, <kbd>Enter</kbd>, <kbd>Space</kbd> and arrow keys, checking that everything is reachable and focus is always visible. Then check images, headings, form labels, landmarks, contrast and media against a checklist, and where possible listen to the page with a screen reader. Automated checkers help, but they catch only a portion of the issues, so manual passes matter.

How does accessibility carry over into React development?

Assistive technology reads the final DOM that React renders, so all the same markup rules apply inside components. ARIA attributes are written as hyphenated props like aria-expanded, the for attribute becomes htmlFor, and state-driven attributes such as aria-invalid or aria-expanded should be derived from the same state that drives the visible UI. Focus management, for example moving focus after a dialog opens or a route changes, remains the developer's responsibility.

23. Quick Revision Checklist

  • One h1 per page, headings descending without jumps, CSS controls appearance.
  • Every image has meaningful alt text, or alt="" if decorative.
  • Every input has a connected label; groups use fieldset and legend.
  • Hints and errors are linked with aria-describedby; invalid fields get aria-invalid.
  • Whole page works with keyboard only; focus outline is always visible; no positive tabindex.
  • One main, labelled nav elements, skip link as the first focusable element.
  • Icon-only controls have aria-label; toggles keep aria-expanded in sync.
  • Dynamic updates are announced through a live region such as role="status".
  • Text meets 4.5:1 contrast, large text 3:1, and colour is never the only signal.
  • Videos have captions, audio has transcripts, nothing autoplays with sound.
  • Tables are used only for data, with caption and scope on headers.
  • Before delivery: a full keyboard pass plus a screen reader pass on every new screen.

Conclusion

Accessibility is not a separate subject bolted onto HTML; it is what good HTML looks like when you take every user seriously. Across these two parts you have moved from the why — real people using real assistive tools — through the core techniques of semantic elements, alt text, labelled forms, keyboard access, ARIA states, landmarks, live regions and contrast, and finished by building and testing a complete accessible page. The same foundation now carries forward into the rest of this course: every React component you write renders HTML that someone will listen to or tab through, and the habits you practised here — name everything, keep state honest, announce changes, test without a mouse — will make your components solid from the first line. Treat the checklist as part of your definition of done, and accessibility becomes not an extra chore but simply the way you build.

Learn more in the React JS Training course, or register for a course demo.

Previous Next
whatsapp