JavaScript document.hasFocus(): Check Whether the Page Has Focus

document.hasFocus() returns a Boolean value indicating whether the current document, or an element inside it, has focus.

const isFocused = document.hasFocus();
console.log(isFocused);
Table of Contents

Check the Current Focus State Top ↑

if (document.hasFocus()) {
  console.log("This document has focus.");
} else {
  console.log("This document does not have focus.");
}

React to Focus and Blur Events Top ↑

If you need to react when focus changes, event listeners are usually better than checking every second.

window.addEventListener("focus", () => {
  console.log("Window focused");
});

window.addEventListener("blur", () => {
  console.log("Window lost focus");
});

Related Plus2net pages: window focus and the existing focus/blur demo.

Periodic Focus Checking Top ↑

The original example used a timer and a string callback. If periodic polling is genuinely required, pass a function callback instead:

const timerId = setInterval(() => {
  console.log(document.hasFocus());
}, 1000);

See the timer tutorial for timer behavior. Do not poll when focus/blur events already solve the problem.

document.hasFocus() vs document.activeElement Top ↑

document.hasFocus() answers whether the document currently has focus. document.activeElement identifies which element is active inside the document.

const focusedDocument = document.hasFocus();
const activeElement = document.activeElement;
console.log(focusedDocument, activeElement);

Focus Is Not the Same as Page Visibility Top ↑

A page can be visible without owning keyboard focus. If the actual requirement is to know whether a tab is hidden, use document.hidden or the visibilitychange event instead.

document.addEventListener("visibilitychange", () => {
  console.log(document.hidden ? "hidden" : "visible");
});
document Object document.lastModified


Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer