HTML DOM hasFocus() method.


The HTML DOM hasFocus() method is used for knowing if the document or any element inside the document has focus. It does so by returning a boolean value in which true represents the document/element has focus and false represents otherwise.

Syntax

Following is the syntax for hasFocus() method −

document.hasFocus()

Example

Let us look at an example for the hasFocus() method −

Live Demo

<!DOCTYPE html>
<html>
<body>
<h1>hasFocus() method</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
<button id="BTN1" >CHECK </button>
<script>
   setInterval("checkFocus()", 20);
   function checkFocus() {
      var b = document.getElementById("BTN1");
      if (document.hasFocus()) {
         b.innerHTML = "FOCUSED";
      } else {
         b.innerHTML = "NOT FOCUSED";
      }
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking any where in the document, the NOT FOCUSED will change to FOCUSED −

In the above example −

We have created a function checkFocus() that gets the button element using the getElementById() method. It then calls the hasFocus() method to know if the document has focus and execute the conditional statements accordingly. It displays different text on the button if the document.hasFocus() returned true or false −

function checkFocus() {
   var b = document.getElementById("BTN1");
   if (document.hasFocus()) {
      b.innerHTML = "FOCUSED";
   } else {
      b.innerHTML = "NOT FOCUSED";
   }
}

Since clicking on the document will always get it focused, we use the setInterval() method that will execute the checkFocus() method every 20 milliseconds to check if the document currently has focus or not −

setInterval("checkFocus()", 20);

Updated on: 19-Feb-2021

66 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements