revision:
The hasFocus() method of the Document interface 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.
The hasFocus() method returns a true if the document (or any element in the document) has focus. Oherwise it returns false.
document.hasFocus()
Parameters: none
<p id="log">Focus check results are shown here.</p>
<button id="newWindow">Open new window</button>
<script>
const body = document.querySelector("body");
const log = document.getElementById("log");
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";
}
}
function openWindow() {
window.open(
"https://developer.mozilla.org/",
"MDN",
"width=640,height=320,left=150,top=150"
);
}
document.getElementById("newWindow").addEventListener("click", openWindow);
setInterval(checkDocumentFocus, 300);
<div>
<p>Click inside this document to get focus.<br> Click outside this document to lose focus.</p>
<p id="focus-1"></p>
</div>
<script>
setInterval("focusFunction()", 1);
function focusFunction() {
let text;
if (document.hasFocus()) {
text = "The document has focus.";
} else {
text = "The document does NOT have focus.";
}
document.getElementById("focus-1").innerHTML = text;
}
</script>
<div>
<p id="log">Focus check results are shown here.</p>
<button id="newWindow">Open new window</button>
</div>
<script>
const body = document.querySelector("body");
const log = document.getElementById("log");
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";
}
}
function openWindow() {
window.open(
"https://www.lwitters.com/",
"MDN",
"width=640,height=320,left=150,top=150"
);
}
document.getElementById("newWindow").addEventListener("click", openWindow);
setInterval(checkDocumentFocus, 300);
</script>