JavaScript Document hasFocus() Method

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline Widely available
Instance method

What You’ll Learn

document.hasFocus() is an instance method that returns a boolean: does this document (or something inside it) currently have focus? (see MDN Document: hasFocus()). Learn how it relates to activeElement, window switching, and five try-it labs.

01

Kind

Instance method

02

Args

None

03

Returns

boolean

04

true

has focus

05

false

no focus

06

Status

Baseline

Introduction

When a user clicks into your page, tabs away, or opens another window, keyboard focus moves. document.hasFocus() answers a simple question: does this document have focus right now?

MDN: the method returns a boolean indicating whether the document or any element inside the document has focus. You can use it to determine whether the active element in a document has focus.

💡
Think: “is this tab/window the active one for typing?”

1) Call document.hasFocus()
2) Get true or false
3) Update UI, pause work, or resume when focus returns
4) Remember: focus ≠ visibility ≠ selection

⚠️
Active element vs focus (MDN)

When viewing a document, an element with focus is always the active element — but an active element does not necessarily have focus. Example from MDN: an active element inside a popup that is not the foreground does not have focus.

Related tutorials: getSelection(), getElementById(), hasPrivateToken().

Understanding document.hasFocus()

An instance method on the Document interface (MDN). It takes no arguments and returns a boolean about document focus.

  • No parameters — call it with empty parentheses (MDN).
  • Returns true — the active element in the document has focus (MDN).
  • Returns false — the active element in the document has no focus (MDN).
  • Scope — document itself or any element inside can provide focus (MDN).
  • Related — pair with Document.activeElement and the Page Visibility API (MDN See also).
  • Not selection — highlighted text is getSelection(), not focus.

📝 Syntax

General form of Document.hasFocus (MDN):

JavaScript
hasFocus()

Parameters

None (MDN).

Return value

false if the active element in the document has no focus; true if the active element in the document has focus (MDN).

MDN quick sample

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

⚡ Quick Reference

GoalCode
Check focusdocument.hasFocus()
Branch on resultif (document.hasFocus()) { ... }
Poll while testingsetInterval(() => console.log(document.hasFocus()), 300)
Active elementdocument.activeElement
Visibilitydocument.visibilityState
MDN statusBaseline Widely available (since Jul 2015)

🔍 At a Glance

Four facts about document.hasFocus().

Returns
boolean

true / false

Args
none

MDN

Means
doc focus?

or child

Status
Baseline

since 2015

📋 When focus is true vs false

SituationTypical hasFocus()Beginner tip
User is typing in this tabtrueDocument (or a child) has focus
User switches to another windowfalseMDN demo opens a new window to show this
Popup not in the foregroundMay be falseActive element may still exist (MDN)
Background tab (visibility)Often falseAlso check visibilityState if needed

Examples Gallery

Examples follow MDN Document: hasFocus() and practical focus patterns.

📚 Getting Started

Read the boolean and react when focus changes.

Example 1 — Simple focus check

Call hasFocus() and branch on the result.

JavaScript
const focused = document.hasFocus();
console.log(focused ? "This document has focus." : "This document does not have focus.");
Try It Yourself

How It Works

The return value is always a boolean. Click the try-it page, then click away to another window to see it flip to false.

Example 2 — MDN-style live status + new window

MDN polls focus and updates a log; opening another window loses focus.

JavaScript
function checkDocumentFocus() {
  if (document.hasFocus()) {
    log.textContent = "This document has focus.";
    body.style.background = "white";
  } else {
    log.textContent = "This document does not have focus.";
    body.style.background = "gray";
  }
}

setInterval(checkDocumentFocus, 300);
Try It Yourself

How It Works

MDN’s demo uses a short interval so the UI stays in sync when you open another window and come back.

📈 Practical Patterns

Events, activeElement, and visibility together.

Example 3 — Update on focus / blur

Listen on window instead of polling when you only need change events.

JavaScript
function report() {
  console.log("hasFocus:", document.hasFocus());
}

window.addEventListener("focus", report);
window.addEventListener("blur", report);
report();
Try It Yourself

How It Works

Window blur / focus fire when the page loses or regains OS-level focus. Re-check hasFocus() inside those handlers.

Example 4 — Pair with activeElement

MDN See also: know both “who is active” and “do we have focus?”

JavaScript
const active = document.activeElement;
console.log("hasFocus:", document.hasFocus());
console.log("activeElement:", active && active.tagName);
Try It Yourself

How It Works

Click a button to change activeElement. Switch windows to change hasFocus() without necessarily clearing the active element concept MDN describes.

Example 5 — Focus + Page Visibility

MDN See also points to the Page Visibility API for related checks.

JavaScript
console.log({
  hasFocus: document.hasFocus(),
  visibilityState: document.visibilityState,
  hidden: document.hidden,
});
Try It Yourself

How It Works

Visibility tells you if the tab is shown; focus tells you if it can receive keyboard input. Use both when pausing media or network work.

🚀 Common Use Cases

  • Pause animations — stop heavy work when the window loses focus.
  • Live status badges — MDN-style “focused / not focused” indicators.
  • Autosave / drafts — flush edits when the user switches away.
  • Multi-window tools — detect which document is in the foreground.
  • With activeElement — know both which control is active and if it has focus (MDN).
  • With visibility — combine tab visibility and focus for richer lifecycle logic.

🧠 How hasFocus() Works

1

User focuses or leaves the document

Clicking the page, another window, or a popup changes focus state.

User
2

Call document.hasFocus()

No arguments — asks if the document (or a child) has focus (MDN).

Call
3

Get a boolean

true when the active element has focus; otherwise false (MDN).

Result
4

Update your app

Pause, resume, restyle, or combine with visibility / activeElement.

📝 Notes

  • MDN: Baseline Widely available since July 2015.
  • MDN: returns a boolean about whether the active element has focus.
  • MDN: focused element is always active, but active does not always mean focused.
  • MDN See also: Document.activeElement and the Page Visibility API.
  • Opening another window typically makes hasFocus() return false (MDN demo).
  • Related: getSelection(), getElementById(), hasPrivateToken().

Browser Support

Document.hasFocus() is Baseline Widely available on MDN (since July 2015). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Document.hasFocus()

Boolean check for whether the document or an element inside it currently has focus.

Baseline Widely available
Google Chrome Supported
Yes
Mozilla Firefox Supported
Yes
Apple Safari Supported
Yes
Microsoft Edge Supported
Yes
Opera Supported
Yes
Internet Explorer Supported (legacy)
Yes
hasFocus() Wide

Bottom line: Use hasFocus to know if this document can receive keyboard focus. Pair with activeElement and Page Visibility when you need richer lifecycle checks.

Conclusion

document.hasFocus() is a tiny, useful boolean API: it tells you whether this document currently has focus. Combine it with activeElement and visibility checks when your app needs a full picture of user attention.

Continue with getSelection(), hasPrivateToken(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use hasFocus() for a quick boolean focus check (MDN)
  • Re-check on window focus/blur (or poll briefly while testing)
  • Remember active ≠ focused in background popups (MDN)
  • Pair with visibilityState for tab lifecycle logic
  • Keep UI feedback clear when focus is lost

❌ Don’t

  • Confuse focus with text selection
  • Assume activeElement always means the page has focus (MDN)
  • Treat visibility alone as a focus substitute
  • Poll forever at high frequency in production without need
  • Forget to test by switching windows / tabs

Key Takeaways

Knowledge Unlocked

Five things to remember about hasFocus()

A boolean check for document focus.

5
Core concepts
🔄02

Args

none

MDN
🎯03

≠ active

can differ

MDN
04

Related

visibility

API
🛡05

Status

Baseline

2015

❓ Frequently Asked Questions

MDN: Document.hasFocus() returns a boolean indicating whether the document or any element inside the document has focus. It can determine whether the active element in a document has focus.
No. MDN marks Document.hasFocus() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
false if the active element in the document has no focus; true if the active element in the document has focus (MDN).
No. MDN: an element with focus is always the active element, but an active element does not necessarily have focus — for example in a popup that is not the foreground.
hasFocus() answers whether this document has keyboard/UI focus. Page Visibility answers whether the page is visible (for example, not in a background tab). They are related but not identical.
No. MDN: hasFocus() takes no parameters.
Did you know?

MDN’s classic demo changes the page background from white to gray whenever document.hasFocus() flips — a visual cue that is easy for beginners to understand while switching windows.

Next: hasPrivateToken()

Learn the experimental Private State Token check for whether an issuer token is already stored.

hasPrivateToken() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful