HTML - DOM Document hasFocus() Method



The hasFocus() method is used for determining if the document or any element inside the document has focus or not. It returns a boolean value where true represents the document/element has focus and false represents otherwise. It represents if active element is in focus or not.

Syntax

document.hasFocus();

Parameter

This method does not accepts any parameter.

Return Value

It returns a boolean value representing if an element or document has focus or not.

Examples of HTML DOM Document 'hasFocus()' Method

The following examples illustrates hasFocus() method.

Check the Document for Focus

The following example shows whether the HTML document has focus or not.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM document hasFocus() Method
    </title>
</head>
<body>
    <p>
        Click the button below to check if 
        document is in focus or not.
    </p>
    <button onclick="fun()">
        Click me
    </button>
    <p id="focus"></p>
    <script>
        setInterval("checkFocus()", 1);
        function fun() {
            let x = document.getElementById("focus");
            if (document.hasFocus()) {
                x.innerHTML = "FOCUSED";
            }
            else {
                x.innerHTML = "NOT FOCUSED";
            }
        }
    </script>
</body>
</html>

Change the Text Color

In the following example, text color of document changes if the document has focus.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM document hasFocus() Method
    </title>
</head>
<body>
    <p>
        Click the button below to check 
        if document is in focus or not.
    </p>
    <button onclick="fun()">
        Click me
    </button>
    <p id="focus">Welcome to Tutorials Point...</p>
    <script>
        setInterval("checkFocus()", 1);
        function fun() {
            let x = document.getElementById("focus");
            if (document.hasFocus()) {
                x.style.color = "#04af2f";
            }
            else {
                x.style.color = "yellow";
            }
        }
    </script>
</body>
</html>

Supported Browsers

Method Chrome Edge Firefox Safari Opera
hasFocus() Yes 2 Yes 12 Yes 3 Yes 4 Yes 15
html_dom_document_reference.htm
Advertisements