HTML | DOM hasFocus() Method

In HTML document, the document.hasfocus() method is used for indicating whether an element or document has focus or not. The function returns true value if the element is focused otherwise false is returned. This method can be used to determine whether the active element is currently in focus.

Syntax

document.hasfocus();

Parameters: This method has no parameters.

Return Value: The hasfocus() method returns a Boolean value indicating whether an element or document has focus or not.

Below examples illustrate the HTML DOM hasfocus() method:

Example 1: This example illustrates whether document has focus or not.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<body>
    <p>Click anywhere in the document to test hasfocus() function.</p>
    <p id="para"></p>
    <script>
        setInterval("hasfocustest()", 1);
  
        function hasfocustest() {
            var x = document.getElementById("para");
            if (document.hasFocus()) {
                x.innerHTML = "The document has focus.";
            } else {
                x.innerHTML = "The document DOES NOT have focus.";
            }
        }
    </script>
</body>
  
</html>

chevron_right


Output:

Initially:

After pressing in the document:

Explanation: The setinterval() function calls the hasfocustest() in 1 milliseconds which after evaluation produces result.

Example 2: This example illustrates changes background-colour of heading based on whether the document has focus or not.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<body>
    <p>Click anywhere in the document to test hasfocus() function.</p>
    <h1 id="para"> Function Testing</h1>
    <script>
        setInterval("hasfocustest()", 1);
  
        function hasfocustest() {
            var x = document.getElementById("para");
            if (document.hasFocus()) {
                x.style.background = "palegreen";
            } else {
                x.style.background = "white";
            }
        }
    </script>
</body>
  
</html>
</html>

chevron_right


Output:

Initially:

After pressing in the document:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.