The hasFocus()
method of the Document
interface returns true or false indicating that document or any component within the document has focus.
hasFocus()
Here is the example that checks whether the document has focus or not
const body = document.querySelector("body");
const log = document.getElementById("log");
if (document.hasFocus()) {
log.textContent = "This document has focus.";
body.style.background = "yellow";
} else {
log.textContent = "This document does not have focus.";
body.style.background = "white";
}