document.hasFocus

This article is in need of a technical review.

Summary

Returns a Boolean value indicating whether the document or any element inside the document has focus. This method can be used to determine whether the active element in a document has focus.

Note: When viewing a document, an element with focus is always the active element in the document, but an active element does not necessarily have focus. For example, an active element within a (popup) window that is not the foreground has no focus.

Syntax

focused = document.hasFocus();

Return value

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

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>TEST</title>
<style>
#message { font-weight: bold; }
</style>

<script>

setInterval( CheckPageFocus(), 200 );

function CheckPageFocus() {
  var info = document.getElementById("message");

  if ( document.hasFocus() ) {
    info.innerHTML = "The document has the focus.";
  } else {
    info.innerHTML = "The document doesn't have the focus.";
  }
}

function OpenWindow() {
  window.open (
    "http://developer.mozilla.org/",
    "mozdev",
    "width=640,
    height=300,
    left=150,
    top=260"
  );
}

</script>
</head>

<body>
  <h1>JavaScript hasFocus example</h1>
  <div id="message">Waiting for user action</div>
  <div><button onclick="OpenWindow()">Open a new window</button></div>
</body>
</html>

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 30 3.0 (1.9) 6.0 Not supported (Yes)
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? 1.0 (1.9) ? Not supported ?

Specification

See also

Hide Sidebar