Document.hasFocus() method 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. 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 does not have focus.
var focused = document.hasFocus();
false if the active element in the document has no focus; true if the active element in the document has focus.
<!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> | Specification | Status | Comment |
|---|---|---|
| HTML Living Standard The definition of 'Document.hasFocus()' in that specification. | Living Standard | Initial definition |
| Desktop | ||||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
| Basic support | 30 | Yes | 3 | 6 | Yes | Yes |
| Mobile | |||||||
|---|---|---|---|---|---|---|---|
| Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
| Basic support | Yes | Yes | Yes | 4 | Yes | Yes | ? |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/document/hasFocus