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);
if (document.hasFocus()) {
console.log("This document has focus.");
} else {
console.log("This document does not have focus.");
}
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.
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() 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);
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
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.