Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dom

How to use the document.hasFocus() method in the DOM

Abdul Muizz

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

In this Answer, we understand the use of the document.hasFocus() method in the Document Object Model (DOM). This method allows us to check if the document, or any element within it, has focus or not.

Note: To learn more about the DOM, we can click here.

Syntax

Now that we know the primary use of this method, let's explore its syntax:

document.hasFocus()

Here, the document object refers to the HTML page that the browser loads.

Return value

This method returns a boolean value. It is true if the document has focus. Otherwise, it is false.

Code

Let's take a look at a working code example:

Explanation

  • Lines 5–9: In these lines of code, we have a parent <div> that encapsulates the web content of our page, described as follows:
    • Line 8: This line includes our placeholder <p> tag, which shows the user if the document has focus or not by displaying the appropriate text.
  • Lines 10–21: This part of the code contains our actual JavaScript code contained within HTML <script> tags, as follows:
    • Line 11: Here, we use the setInterval() method, which repeatedly calls the hasfocus() function after a time interval of one millisecond. To read more on setInterval(), please refer to this Answer.
    • Line 13: This line of code is within the body of our hasfocus() function. Here, we use the document.getElementById() method to get hold of our placeholder <p> tag.
    • Lines 14–19: In these lines, we use the document.hasFocus() method in if-else statements, and decide to render the appropriate text using the innerHTML property inside our <p> tag.

Note: To read more on document.getElementById() and the innerHTML property, please take a look at the following Answers:

RELATED TAGS

dom

CONTRIBUTOR

Abdul Muizz
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring