Understanding document.hasFocus() in Modern JavaScript

Learn how to detect page focus with JavaScript for better user experiences, performance optimization, and accessible web applications.

What is document.hasFocus()?

The document.hasFocus() method is a built-in JavaScript function that returns a boolean value indicating whether the document or any element within the document currently has focus. When the user clicks on a page element or tabs into the document, the method returns true. When the user switches to another tab, window, or application, it returns false.

This method is part of the Document interface and requires no parameters. It's supported across all modern browsers and has been available since the early days of DOM manipulation, making it a reliable tool for focus detection.

For developers building web applications, understanding focus detection is essential for creating polished, professional user experiences.

Syntax and Return Value

const isFocused = document.hasFocus();

The method takes no parameters and returns:

  • true if the document or any element inside it has focus
  • false if the document and all its elements have lost focus

Key Distinction: hasFocus() vs activeElement

While document.hasFocus() tells you whether the page has focus overall, document.activeElement tells you specifically which element has focus. These two APIs serve different purposes:

  • Use hasFocus() when you need to know if the user is currently interacting with the page at all
  • Use activeElement when you need to know which specific element has focus

Use document.activeElement to check if a specific element has focus:

const input = document.getElementById('username');
const inputHasFocus = input === document.activeElement;

Use contains() to check if focus is within a container:

const modal = document.getElementById('modal');
const focusInsideModal = modal.contains(document.activeElement);
Practical Use Cases

Common scenarios where document.hasFocus() improves user experience and performance

Pause Animations and Media

Stop animations and video playback when users switch tabs to save resources and battery life.

Real-Time Status Updates

Reduce polling frequency when the page is in background to improve performance.

Form Auto-Save

Automatically save form data when users navigate away from the page.

Modal Focus Management

Properly manage focus for accessible modal dialogs and overlay components.

Real-Time Focus Monitoring

For applications that need accurate focus state at all times, combining hasFocus() with event listeners provides the most reliable solution:

function setupFocusMonitoring() {
 const statusDisplay = document.getElementById('focus-status');

 function updateFocusState() {
 const hasFocus = document.hasFocus();
 statusDisplay.textContent = hasFocus
 ? 'Page is active'
 : 'Page is in background';
 statusDisplay.className = hasFocus ? 'status-active' : 'status-inactive';
 }

 // Initial check
 updateFocusState();

 // Continuous monitoring
 setInterval(updateFocusState, 1000);

 // Immediate updates on focus changes
 window.addEventListener('focus', updateFocusState);
 window.addEventListener('blur', updateFocusState);
}

This approach ensures:

  • Initial state is captured correctly
  • Changes are detected immediately
  • Periodic checks catch any missed events

Implementing focus monitoring patterns like this is essential for optimizing web application performance and delivering smooth user experiences.

Modern CSS Approaches to Focus Detection

Modern CSS provides powerful alternatives to JavaScript for focus detection that can simplify your code and improve performance.

Using :focus-within

The :focus-within pseudo-class matches an element when it or any of its descendants has focus:

// Close all navs that don't have focus within them
const navsToClose = document.querySelectorAll('nav[open]:not(:focus-within)');
navsToClose.forEach(nav => nav.close());

Using :has() with :focus

The :has() pseudo-class allows checking for descendants with focus:

// Check if an element contains a focused element
const modal = document.getElementById('modal');
const hasFocusedChild = modal.matches(':has(:focus)');

// Find all modals with focused children
const activeModals = document.querySelectorAll('.modal:has(:focus)');

When to Use CSS vs JavaScript:

Use CSS-based focus detection when:

  • You're already styling based on focus state
  • You need to select elements efficiently
  • The focus check is for UI updates

Use JavaScript focus detection when:

  • You need to trigger actions based on focus changes
  • You're building complex focus management systems
  • You need to store or analyze focus history

These CSS techniques complement traditional JavaScript focus management for optimal results.

Best Practices

Guidelines for effective and accessible focus management

Performance Optimization

Use event listeners instead of polling, implement throttling for expensive operations, and clean up listeners when components unmount.

Accessibility First

Never trap focus without user intent, provide visual focus indicators, and manage focus properly for modals and dialogs.

Error Handling

Handle edge cases like iframes, popups, and cross-origin scenarios. Provide graceful fallbacks for older browsers.

Component Isolation

Keep focus management contained within components rather than spreading across the application.

React Hook for Focus Detection
1import { useState, useEffect } from 'react';2 3export function usePageFocus() {4 const [isFocused, setIsFocused] = useState(true);5 6 useEffect(() => {7 const handleFocus = () => setIsFocused(true);8 const handleBlur = () => setIsFocused(false);9 const updateFocus = () => setIsFocused(document.hasFocus());10 11 window.addEventListener('focus', handleFocus);12 window.addEventListener('blur', handleBlur);13 const interval = setInterval(updateFocus, 1000);14 15 return () => {16 window.removeEventListener('focus', handleFocus);17 window.removeEventListener('blur', handleBlur);18 clearInterval(interval);19 };20 }, []);21 22 return isFocused;23}

Frequently Asked Questions

Build Better Web Applications with Expert Focus Management

Our team specializes in creating performant, accessible web applications with proper focus management and modern JavaScript patterns.