HTML
Keyboard navigation
Learn tab order, tabindex and focus management.
Tab order and tabindex
Keyboard users move through a page with the Tab key. The natural order is the HTML source order of focusable items: links, buttons and inputs. Leaving this order untouched is best.
When you must intervene, the tabindex attribute helps: tabindex="0" puts an element into the normal flow; tabindex="-1" removes it from the flow but keeps it focusable through JavaScript; tabindex="1" and above should be avoided, since it rewrites the order.
Focus management
When an element opens and closes, focus must go to the right place. When a menu opens, focus moves to its first item; when it closes, focus returns to the triggering button. This is called focus management.
When a modal opens, focus moves into it; on close, focus returns to the trigger. Otherwise a keyboard user who cannot see the screen loses track of where focus is. JavaScript's .focus() call handles this.
Exercise Write a skip link and focusable regions
Add a skip link inside body: <a href="#content">Skip to content</a>. Then open a <main id="content">. Inside main put a <button> and a <div>. The button should have non-empty text. Give the div tabindex="0" so the keyboard can focus it. Close main.
Show example solution
<body>
<a href="#content" class="skip-link">Skip to content</a>
<main id="content">
<button>Open menu</button>
<div tabindex="0" role="region">Quick info</div>
</main>
</body>
Test yourself
-
What does tabindex="-1" do?
- Removes the element from Tab flow but keeps it JS-focusable
- Puts the element at the start of the Tab flow
- Makes the element full screen
- Hides the element
Show answer
Removes the element from Tab flow but keeps it JS-focusable — Correct. -1 drops the element from Tab order but keeps it focusable through JavaScript; ideal for programmatic focus.
-
Complete the skip link target
<body>
<a href="#____" class="skip-link">Skip to content</a>
<main id="content">...</main>
</body>
Show answer
<body>
<a href="#content" class="skip-link">Skip to content</a>
<main id="content">...</main>
</body>
-
Match each tabindex value to its behaviour
- tabindex="0"
- Enters normal Tab flow
- tabindex="-1"
- Out of Tab but focusable
- tabindex="1"
- Rewrites order, avoid
- no tabindex
- Natural HTML order
-
When a modal closes, where should focus go?
- Top of the page
- To body
- Next section
- Back to the triggering button
Show answer
Back to the triggering button — Correct. The button that opened the modal receives focus back; the user knows where they are.
Next lesson: Live regions