Skip to content

Programmatic Focus — Using element.focus() and Its Options

DodaTech Updated 2026-06-28 3 min read

In this tutorial, you will learn about Programmatic Focus. We cover key concepts, practical examples, and best practices to help you master this topic.

Programmatic focus with element.focus() moves keyboard focus via JavaScript, with options like preventScroll and the FocusOptions parameter for controlling focus behavior.

In this tutorial, you'll learn advanced Focus Management with element.focus().

What You'll Learn

By the end of this lesson, you'll understand how to use element.focus() with options, when to use programmatic focus, and how to avoid common pitfalls.

Why It Matters

Programmatic focus is the primary tool for focus management. Using it incorrectly can confuse users or cause unexpected scrolling.

Real-World Use

Durga Antivirus Pro uses element.focus() to move focus to scan results, error summaries, and modal dialogs.

Focus Options

flowchart LR
  A[element.focus()] --> B[focus({ preventScroll: false })]
  A --> C[focus({ preventScroll: true })]
  B --> D[Scrolls element into view]
  C --> E[Focuses without scrolling]
  B --> F[Default behavior]
  C --> G[Use for offscreen elements]

Basic Usage

// Focus an element
document.getElementById('search-input').focus();

// Focus with preventScroll
document.getElementById('error-summary').focus({ preventScroll: true });

// Focus the first focusable element
function focusFirstElement(container) {
  const focusable = container.querySelector(
    'a[href], button, input, textarea, select, [tabindex]:not([tabindex="-1"])'
  );
  if (focusable) focusable.focus();
}

Focus on Dynamic Content

// Focus heading after SPA navigation
function navigateToPage(url) {
  loadContent(url).then(() => {
    document.querySelector('main h1').setAttribute('tabindex', '-1');
    document.querySelector('main h1').focus({ preventScroll: true });
  });
}

// Focus error after form validation
function showErrors(errors) {
  const summary = document.getElementById('error-summary');
  summary.innerHTML = errors.map(e => `<li>${e}</li>`).join('');
  summary.setAttribute('tabindex', '-1');
  summary.focus();
}

FocusOptions

The FocusOptions object supports:

Option Type Default Description
preventScroll boolean false Prevents the browser from scrolling the element into view
// Focus without scrolling (useful for offscreen elements)
element.focus({ preventScroll: true });

// Default: scroll into view
element.focus(); // equivalent to focus({ preventScroll: false })

Common Mistakes

  • Calling focus() on a hidden element: The focus will not work. Ensure the element is visible.
  • Calling focus() on a non-focusable element: Elements without tabindex="0" or "-1" cannot receive focus.
  • Not using preventScroll when appropriate: Unwanted scrolling disorients users.
  • Calling focus() before the element is in the DOM: The element must exist before focusing.
  • Focusing elements unnecessarily: Only move focus when the context changes.

Practice and Challenge

1. What method moves focus programmatically? element.focus().

2. What option prevents scrolling during focus? { preventScroll: true }.

3. Why add tabindex="-1" to a heading before focusing it? Because headings are not focusable by default.

4. When should you NOT move focus programmatically? When there is no meaningful context change.

5. Challenge: Create a single-page app navigation that focuses the new page heading when the route changes.

FAQ

Can I focus a disabled element?

No. Disabled elements cannot receive focus.

Does focus() work on hidden elements?

No. The element must be visible (not hidden or display:none).

What happens if I focus a non-existent element?

Nothing. The focus call is silently ignored.

Can I use focus() on any role?

Focus only works on elements with an implicit or explicit tabindex.

Does focus() trigger the :focus CSS selector?

Yes. Focus applies the :focus CSS pseudo-class.

Mini Project

Build a form with real-time validation. When validation fails, use programmatic focus to move focus to the first error message with a focusable error summary.

What's Next

Continue to Focus When Dialog Opens to learn about moving focus to the correct element on dialog open.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro