Sikau

Web essentials · Day 9 · about 30 min

Keyboard and focus

Everything reachable, nothing lost.

Put the mouse away

Many people navigate with only a keyboard — by choice, injury or disability. Try it: Tab moves forward, Shift+Tab back, Enter and Space activate. If something can only be done with a mouse, they're locked out. Managing focus well is the fix.

tabindex and moving focus

const open = document.querySelector("#open");
const panel = document.querySelector("#panel");
const close = document.querySelector("#close");

open.addEventListener("click", () => {
  panel.hidden = false;
  panel.querySelector("h2").focus();
});
close.addEventListener("click", () => {
  panel.hidden = true;
  open.focus();
});
  • Native controls (button, a[href], input) are focusable already.
  • tabindex="0" adds an element to the tab order (only for custom widgets).
  • tabindex="-1" makes it focusable by script but skips it when tabbing (headings you move focus to).
  • Never use positive tabindex values — they scramble the order.
  • Keep a visible focus style. Hidden things (hidden, display: none) aren't focusable.

The rest of this lesson

  • Managing focus in dynamic UIsexplain
  • Visible focus and the Escape keyexplain
  • Can you Tab to it?predict
  • Where should focus go?match
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 16 lessons of Web essentials