You are here: Reference > JavaScript > client-side > HTML DOM > methods > hasFocus (document)

hasFocus method (document)

Browser support:
3
Returns a Boolean value indicating whether the document or any element in the document has focus.
Note: The hasFocus method is supported in Firefox from version 3.
The hasFocus method can be useful to determine whether the active element in a document has focus.
An element with focus is always the active element in a document, but an active element does not necessarily have focus. For example, an active element within a window that is not the foreground window has no focus.
Use the activeElement property to retrieve and the focus and setActive methods to set the active element in a document.

Syntax:

object.hasFocus ( );
You can find the related objects in the Supported by objects section below.

Return value:

Boolean. One of the following values:
false The active element in the document has no focus.
true The active element in the document has focus.

Example HTML code 1:

This example illustrates the use of the hasFocus method:
Code
focusTest.htm
<head>
    <script type="text/javascript">
        function Init () {
            if (document.hasFocus)
                setInterval ("CheckFocus ()", 200);
            else
                alert ("Your browser does not support the hasFocus method");
        }

        function CheckFocus () {
            var info = document.getElementById ("info");
            if (document.hasFocus ()) {
                info.innerHTML = "The document has the focus.";
            }
            else {
                info.innerHTML = "The document doesn't have the focus.";
            }
        }

        function OpenTestWindow () {
            window.open ("focusTest.htm", "testWindow", "width=250, height=150, left=10, top=10");
        }
    </script>
</head>
<body onload="Init ();">
    <div id="info"></div>

    <br /><br />
    Opening the test window will cause the focus to be lost. <br />
    <button onclick="OpenTestWindow ();">Open the test window</button>
</body>
Did you find this example helpful? yes no

Supported by objects:

Related pages:

External links:

User Contributed Comments
In Google Chrome, this function always returns true. There's a bug tracker for it:

http://code.google.com/p/chromium/issues/detail?id=64846

Post Content

Post Content