Sobes.tech
Junior

What are the ways to set focus on an element?

sobes.tech AI

Answer from AI

element.focus()

// Setting focus on an input when the page loads
window.addEventListener('load', () => {
  const inputElement = document.getElementById('myInput');
  if (inputElement) {
    inputElement.focus();
  }
});

autoFocus attribute for HTML elements:

<input type="text" autoFocus>

Programmatic focus setting using requestAnimationFrame:

// Delayed focus setting
requestAnimationFrame(() => {
  const elementToFocus = document.getElementById('targetElement');
  if (elementToFocus) {
    elementToFocus.focus();
  }
});

Using tabIndex:

<div id="focusableDiv" tabindex="0">
  This div can now be focused.
</div>

Scripted focus management in SPA:

// Moving focus when navigating between pages in React
useEffect(() => {
  const headingElement = document.getElementById('pageHeading');
  if (headingElement) {
    headingElement.focus();
  }
}, [location.pathname]); // Depends on URL change

Accessibility considerations for focus management:

  • Ensure the focus is visible (style outline).
  • Follow natural focus order (DOM structure, tabIndex > 0).
  • Manage focus when opening modal or popup windows.
  • Return focus to the original element after closing interactive elements.
  • Use aria-live regions to notify screen readers of changes affecting focus.