Skip to main content
Saved

Pattern Accessibility Beginner

Live Regions

ARIA live regions let screen readers announce content that changes on the page. You choose a politeness level for each region, depending on how urgent its messages are.

Examples
React, Vue and native web
Read
4 min

The problem

A user clicks “Add to Cart” and a toast appears saying “Item added!”, but screen reader users hear nothing. The page didn’t reload, so the screen reader doesn’t announce the new content, and users can’t tell whether their action worked.

The pattern

Once you mark a region of your page with aria-live, screen readers announce changes to its content automatically.

Problem

I’ve tested e-commerce sites where screen readers didn’t announce cart updates at all. Users who heard nothing after clicking “Add” assumed it had failed, and they ended up adding the same item multiple times or giving up.

Form validation has the same problem. Error messages appear inline but never get announced, so users might submit invalid data again and again without knowing what’s wrong. Auto-save indicators that briefly show “Saved” don’t get announced either.

Solution

aria-live="polite" is for non-urgent updates, such as “Item added to cart,” which the screen reader announces after it finishes its current announcement. aria-live="assertive" is for urgent messages that should interrupt immediately, like an error that stops the user from continuing.

As a shorthand, role="status" works the same way as aria-live="polite", and role="alert" works the same way as aria-live="assertive". Each role also implies aria-atomic="true", which makes the screen reader announce the region’s whole text instead of only the part that changed. You only need the role or the attribute, and the examples below use the roles.

The live region container has to be in the DOM before you add content to it. Usually, that means adding an empty <div role="status"> when the page loads, and then putting messages into it as things happen. If you create the region and its content at the same time, the message often isn’t announced, because screen readers might miss the new region.

A region is only announced when its text changes. If your code sets the same message twice in a row, screen readers don’t announce the second one, which is why the examples below clear a message after a few seconds or before setting it again.

Example

These examples use live regions for a status update, a form’s error messages, and an upload’s progress.

Basic Live Regions

Most toasts are written like the line below, which adds the region and its message to the DOM together. That line is the reason screen readers didn’t announce the “Item added!” toast in the Problem.

{message && <div role="status">{message}</div>}

In the working versions, the region is always rendered, and only its text changes.

<!-- Polite: announced after the current announcement finishes -->
<div role="status" class="sr-only"></div>

<!-- Assertive: interrupts immediately -->
<div role="alert" class="sr-only"></div>

<script>
  // The empty regions above are in the page from the start
  function announce(text) {
    document.querySelector('[role="status"]').textContent = text;
  }
</script>

The sr-only class hides the region visually while keeping it available to screen readers, for cases where sighted users already get the message from a toast.

.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
  border: 0;
}

Form Validation Announcements

Validation errors are a good fit for an assertive region, because users need to know what’s stopping the form from submitting. The region below contains the messages themselves, so users hear which fields they need to fix. Each inline message is also connected to its input with aria-describedby, so the screen reader repeats it when the user moves to that field.

function SignupForm() {
  const [errors, setErrors] = useState({});
  const [errorMessage, setErrorMessage] = useState('');

  const validateForm = (formData) => {
    const newErrors = {};
    if (!formData.email) newErrors.email = 'Email is required';
    if (!formData.password) newErrors.password = 'Password is required';
    setErrors(newErrors);

    const messages = Object.values(newErrors);
    // Clear first, so the same errors are announced again on the next submit
    setErrorMessage('');
    if (messages.length > 0) {
      setTimeout(() => setErrorMessage(messages.join('. ')), 100);
    }
    return messages.length === 0;
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    const formData = Object.fromEntries(new FormData(e.target));
    if (validateForm(formData)) {
      // submit the form
    }
  };

  return (
    <form onSubmit={handleSubmit} noValidate>
      <div role="alert" className="sr-only">{errorMessage}</div>
      <div>
        <label htmlFor="email">Email</label>
        <input id="email" name="email" type="email"
          aria-invalid={!!errors.email} aria-describedby="email-error" />
        <p id="email-error">{errors.email}</p>
      </div>
      <div>
        <label htmlFor="password">Password</label>
        <input id="password" name="password" type="password"
          aria-invalid={!!errors.password} aria-describedby="password-error" />
        <p id="password-error">{errors.password}</p>
      </div>
      <button type="submit">Sign Up</button>
    </form>
  );
}

Progress Indicator

The upload’s progress is only announced at each 25% milestone, instead of at each percentage change, so there aren’t too many announcements. The same applies to anything that updates quickly, such as a result count that changes as the user types in a search box, where the announcement should be delayed until they’ve stopped typing.

function FileUpload() {
  const [progress, setProgress] = useState(0);
  const [announcement, setAnnouncement] = useState('');

  const updateProgress = (percent) => {
    setProgress(percent);
    if (percent % 25 === 0) setAnnouncement(`Upload ${percent}% complete`);
  };

  return (
    <>
      <div role="progressbar" aria-label="Upload progress" aria-valuenow={progress} aria-valuemin="0" aria-valuemax="100">
        <div style={{ width: `${progress}%` }} />
      </div>
      <div role="status" className="sr-only">{announcement}</div>
    </>
  );
}

Benefits

  • Screen reader users hear about content that changes on the page, even when the page doesn’t reload.
  • Messages are announced automatically, so users don’t have to search through the page to find what changed.
  • Live regions work with the major screen readers, including NVDA, JAWS, and VoiceOver, without any special setup.
  • Users can hear about loading states and progress milestones as they happen.
  • The feedback that sighted users get visually is also available to screen reader users.

Tradeoffs

  • Too many announcements turn into noise and can make an app unusable for screen reader users, so you should use live regions sparingly.
  • You have to choose the right politeness level for each region, because assertive interrupts immediately and should be rare, while a polite message is announced after the screen reader finishes its current announcement, and should be your default.
  • Rapid updates, such as stock prices or chat messages, can overwhelm screen reader users, so you might need to throttle or batch the announcements.
  • NVDA, JAWS, and VoiceOver each handle the timing of announcements a little differently, so it’s worth testing with more than one of them.
  • The content has to stay in the region long enough to be announced, and if your code clears it too quickly, users hear nothing.
  • With role="status" and role="alert", screen readers announce the entire region each time. For a region where only the changed part should be announced, such as a chat log, you need aria-live with aria-atomic="false" instead.
  • Automated testing can’t check whether announcements make sense, so you still need to test with a real screen reader.

Summary

Live regions let screen readers announce content that changes on the page, for users who can’t see the visual updates. aria-live="polite" is for routine updates, and aria-live="assertive" is for the occasional critical alert. The region has to be in the DOM before its content changes, because screen readers announce a message when the text inside an existing region changes.

See also

Next in Accessibility Accessible Forms Forms with proper labels and announced error messages, so screen reader users and keyboard users can fill them in too.

A monthly email
from Den Odell.

What I'm thinking about frontend patterns, plus news when the site changes.

No spam. Unsubscribe anytime.