How o check if a window is in focus?

 

Document.hasFocus()

The hasFocus() method of the Document interface returns true or false indicating that document or any component within the document has focus.

 

Syntax

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";
  }


 


Tags:

Share:

Related posts