Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

HTML | DOM hasFocus() Method

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In HTML document, the document.hasfocus() the method is used for indicating whether an element or document has the focus or not. The function returns a 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. 

html




<!DOCTYPE html>
<html>
    <title>
        HTML | DOM hasFocus() Method
    </title>
<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>                   

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. 

html




<!DOCTYPE html>
<html>
<head>
    <title>
        HTML | DOM hasFocus() Method
    </title>
</head>
<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>

Output:

Initially

 

After pressing in the document:

  

Supported Browser: The browsers supported by method are listed below:

  • Google Chrome 1
  • Edge 12
  • Internet Explorer 5.5
  • Firefox 3
  • Opera 15
  • Safari 4

My Personal Notes arrow_drop_up
Last Updated : 13 Jul, 2022
Like Article
Save Article
Similar Reads
Related Tutorials