Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 35 ยท Quality

Accessibility in Svelte and the a11y Warnings

Build accessible Svelte apps - the compiler's a11y warnings explained, semantic HTML, labels, keyboard support, focus management, ARIA live regions and svelte-ignore.

Accessibility (a11y) means people can use your app with a keyboard, a screen reader, zoom, or reduced motion. It is not an extra: a large share of users depend on at least one of those, and the same fixes (real buttons, labels, focus order) make an app better for everyone. Svelte helps by checking your markup at compile time and warning about common mistakes.

The Svelte compiler is not available on this site, so Svelte markup is read-only. The <TryIt> blocks run a small a11y checker written in plain JavaScript over markup strings, mimicking a few of the compiler's rules, and demonstrate focus and live-region logic.

The compiler warns you

Write this and Svelte prints a warning during npm run dev or build, and in your editor:

HTML
<div onclick={save}>Save</div>
TEXT
a11y_click_events_have_key_events: Visible, non-interactive elements with a click event
must be accompanied by a keyboard event handler.
a11y_no_static_element_interactions: <div> with a click handler must have an ARIA role

A <div> is not focusable and does not respond to Enter or Space, so keyboard users cannot activate it. The cleanest fix is not to add roles and key handlers but to use the right element:

HTML
<button type="button" onclick={save}>Save</button>

A <button> is focusable, activates with Enter and Space, has the role "button" and is announced by screen readers, all for free.

Some warnings you will meet:

Warning Meaning Fix
a11y_missing_attribute <img> without alt, <a> without href add alt (empty alt="" if decorative)
a11y_label_has_associated_control <label> not tied to an input wrap the input or use for/id
a11y_click_events_have_key_events click without keyboard handler use a <button> or <a>
a11y_no_noninteractive_element_interactions handler on <p>, <li> etc. move it to a real control
a11y_autofocus autofocus attribute manage focus deliberately
a11y_distracting_elements <marquee>, <blink> do not use
a11y_media_has_caption <video> without <track kind="captions"> add captions
a11y_misplaced_role, a11y_unknown_role invalid ARIA role use a valid role

Treat warnings as errors in CI. In rare, justified cases silence one with a comment and a reason:

HTML
<!-- svelte-ignore a11y_no_static_element_interactions (backdrop closes the dialog, Escape also works) -->
<div class="backdrop" onclick={close}></div>

A mini checker

This stand-in scans markup for three of these mistakes. The real compiler works on a parsed tree and knows many more rules, but the idea is identical.

JS Find the accessibility mistakes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Semantic HTML first

Most accessibility is choosing the right element:

  • <button> for actions, <a href> for navigation. Never a click handler on a <div>.
  • <nav>, <main>, <header>, <footer>, <aside> for landmarks, so assistive technology can jump around.
  • One <h1>, then headings in order (h2 under h1).
  • Lists as <ul>/<ol>, tables as <table> with <th scope>.
  • Every form control has a visible <label>. Use aria-label only when there is no visible text (an icon button).
HTML
<button type="button" onclick={() => (open = !open)} aria-expanded={open} aria-controls="menu">
  Menu
</button>
<ul id="menu" hidden={!open}>...</ul>

aria-expanded tells screen readers the current state of a disclosure. Keep ARIA for things HTML cannot express; "no ARIA is better than bad ARIA".

Keyboard and focus

Everything usable with a mouse must work with the keyboard: Tab moves between controls, Enter/Space activate, Escape closes. Check your whole app by unplugging the mouse for five minutes.

Focus management matters when content changes without a page load. After opening a modal, move focus into it; on close, return focus to the button that opened it. In Svelte, bind:this plus $effect does it:

HTML
<script>
  let { open, onclose, children } = $props();
  let dialog;
  let opener;

  $effect(() => {
    if (open) {
      opener = document.activeElement;
      dialog.focus();
      return () => opener?.focus();
    }
  });
</script>

{#if open}
  <div bind:this={dialog} role="dialog" aria-modal="true" aria-label="Settings" tabindex="-1"
       onkeydown={(e) => e.key === 'Escape' && onclose()}>
    {@render children()}
    <button type="button" onclick={onclose}>Close</button>
  </div>
{/if}

For modal dialogs the native <dialog> element with showModal() gives you focus trapping and Escape handling without custom code: prefer it. Keep a visible focus outline; if you restyle it, make the replacement at least as clear.

After a client-side route change SvelteKit moves focus to the page body and announces the new title via a live region, so keep <title> unique per page.

Live regions

Dynamic messages ("Saved", "3 results") are invisible to screen reader users unless announced. Put them in an aria-live region that exists in the DOM before its text changes:

HTML
<p role="status" aria-live="polite">{message}</p>   <!-- polite: waits for a pause -->
<p role="alert">{errorText}</p>                      <!-- assertive: interrupts -->

Use polite for most updates and alert only for urgent errors.

JS Focus order and a live-region announcer

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Color, contrast and motion

  • Text needs a contrast ratio of at least 4.5:1 against its background (3:1 for large text). Browser devtools show the ratio.
  • Never rely on color alone: pair a red border with an error message.
  • Respect prefers-reduced-motion, as covered in Transitions: shorten or disable big movements.
  • Support zoom to 200% and text resizing; use relative units.

Testing accessibility

  1. Fix every compiler warning.
  2. Tab through each page.
  3. Use a screen reader on a key flow (NVDA on Windows, VoiceOver on macOS).
  4. Run an automated checker such as axe in Playwright or the browser extension; it finds roughly a third of issues.
  5. Query by role in component tests, as shown in Testing Svelte: if a button cannot be found by role, a screen reader cannot find it either.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the best fix for <div onclick={save}>Save</div>?

    A real button is focusable, works with Enter and Space and has the right role. Roles and key handlers on a div recreate it badly.
  2. 2. What alt text should a purely decorative image have?

    An empty alt tells screen readers to skip the image. A missing alt triggers a warning because readers may read the file name.
  3. 3. Why use role="status" or aria-live on a message?

    Live regions are watched by assistive technology; changes inside them are read aloud.
  4. 4. Where should focus go when a modal dialog opens?

    Moving focus into the dialog keeps keyboard users in context; returning it afterwards stops them losing their place.

Summary

  • The Svelte compiler emits a11y_* warnings; fix them, do not silence them without a reason.
  • Choose semantic elements first (button, a, label, landmarks); ARIA fills gaps.
  • Support the keyboard, manage focus for dialogs and route changes, announce updates with live regions.
  • Keep contrast at 4.5:1 or more, do not rely on color alone and respect reduced motion.
  • Test with the keyboard, a screen reader and automated tools like axe.

Next: Debugging and Performance