Course contentsShow
← Web Development
Lesson 1046 of 2,98219. Keyboard Navigation and FocusFree lesson

tabindex='-1' for Programmatic Focus

Removing elements from tab order while keeping them focusable via JavaScript for component patterns.

What You'll Learn

You'll learn how to remove elements from the keyboard tab order while keeping them focusable through JavaScript—essential for building accessible custom components.

Understanding tabindex="-1"

Setting tabindex="-1" on an element creates a special state: the element won't appear in the natural tab order, but can still receive focus programmatically via JavaScript's focus() method.

This is different from tabindex="0" (which adds elements to the tab order) and from having no tabindex at all (which makes non-interactive elements unfocusable).

Why This Matters

Imagine a modal dialog. When it opens, you want focus to jump immediately to a heading or message inside—but you don't want users accidentally tabbing onto that heading while navigating the page normally. The heading should only receive focus when you explicitly send it there.

This pattern appears frequently in:

  • Skip links that become visible on focus
  • Dialog headings that announce content to screen readers
  • Error messages that need immediate attention
  • Panels or sections that open/close dynamically

How It Works

When an element has tabindex="-1":

  • Pressing Tab will skip right over it
  • Calling element.focus() in JavaScript will work
  • Screen readers can navigate to it when focused
  • The element can receive a visible focus indicator

Think of it like a backstage door: not on the main path through the theater, but accessible when someone with a key (JavaScript) specifically opens it.

Common Pattern

<h2 tabindex="-1" id="dialog-title">Important Message</h2>

Then in JavaScript, you'd focus it when appropriate (you'll learn the exact syntax later).

Key Takeaway: Use tabindex="-1" to remove elements from the tab order while preserving the ability to focus them programmatically—perfect for managing focus in dynamic components and ensuring users land exactly where they need to be.