HTML Document hasFocus()
Method: Checking Focus
The document.hasFocus()
method in HTML DOM is a boolean function that checks whether the document, or any element inside it, currently has focus. This method is incredibly useful for creating interactive web applications where you need to know if the user is actively engaged with your page.
Definition and Purpose
The document.hasFocus()
method determines if the document, or any element within it, has focus. This is crucial for implementing features that depend on user interaction, such as:
- Detecting when a user switches away from the page.
- Pausing or resuming activities based on focus state.
- Modifying UI elements based on whether the document is active.
Syntax
The syntax for using the hasFocus()
method is straightforward:
let hasFocus = document.hasFocus();
- Return Value: A boolean value.
true
if the document or an element within it has focus; otherwise,false
.
Practical Examples
Let’s explore several practical examples to demonstrate how to use the document.hasFocus()
method effectively.
Basic Example: Checking Initial Focus
This example checks if the document has focus when the page loads.
<!DOCTYPE html>
<html>
<head>
<title>hasFocus() Basic Example</title>
</head>
<body>
<p id="focusStatus">Document has focus: Unknown</p>
<script>
const focusStatusElem_basic = document.getElementById("focusStatus");
function checkFocus_basic() {
const hasFocus = document.hasFocus();
focusStatusElem_basic.textContent =
"Document has focus: " + hasFocus;
}
window.onload = checkFocus_basic;
</script>
</body>
</html>
Output:
Initially, the output will depend on whether the browser tab is active when the page loads. It will display “Document has focus: true” or “Document has focus: false” accordingly.
Detecting Focus Changes
This example uses event listeners to detect when the document gains or loses focus.
<!DOCTYPE html>
<html>
<head>
<title>Detecting Focus Changes</title>
</head>
<body>
<p id="focusStatusChange">Document has focus: Unknown</p>
<button id="myButtonChange">Click Me</button>
<script>
const focusStatusElem_change = document.getElementById(
"focusStatusChange"
);
const myButtonChange = document.getElementById("myButtonChange");
function updateFocusStatus_change() {
const hasFocus = document.hasFocus();
focusStatusElem_change.textContent =
"Document has focus: " + hasFocus;
}
document.addEventListener("focus", updateFocusStatus_change);
document.addEventListener("blur", updateFocusStatus_change);
myButtonChange.addEventListener("focus", () => {
console.log("Button has focus");
});
myButtonChange.addEventListener("blur", () => {
console.log("Button lost focus");
});
</script>
</body>
</html>
Instructions:
- Open the HTML page in a browser.
- Initially, the focus status will show “Unknown”.
- Click inside the document, and the status will change to “true”.
- Click outside the document (e.g., on the browser’s address bar), and the status will change to “false”.
- Click the “Click Me” button to give it focus and see the console log.
- Click elsewhere on the page to remove focus from the button and see the console log.
Pausing and Resuming Activities
This example simulates pausing and resuming a video based on the document’s focus state.
<!DOCTYPE html>
<html>
<head>
<title>Pausing and Resuming Activities</title>
</head>
<body>
<video id="myVideoPause" width="320" height="176" controls>
<source
src="https://www.w3schools.com/html/mov_bbb.mp4"
type="video/mp4"
/>
Your browser does not support HTML5 video.
</video>
<script>
const videoElement_pause = document.getElementById("myVideoPause");
function checkFocusAndToggle_pause() {
if (document.hasFocus()) {
if (videoElement_pause.paused) {
videoElement_pause.play();
console.log("Video playing");
}
} else {
if (!videoElement_pause.paused) {
videoElement_pause.pause();
console.log("Video paused");
}
}
}
document.addEventListener("focus", checkFocusAndToggle_pause);
document.addEventListener("blur", checkFocusAndToggle_pause);
</script>
</body>
</html>
Instructions:
- Open the HTML page in a browser.
- Play the video.
- Click outside the browser window to move focus away from the document. The video will pause.
- Click back inside the browser window to give focus to the document. The video will resume playing.
Modifying UI Based on Focus
This example changes the background color of a div based on whether the document has focus.
<!DOCTYPE html>
<html>
<head>
<title>Modifying UI Based on Focus</title>
<style>
#myDivUI {
width: 200px;
height: 100px;
background-color: lightblue;
text-align: center;
line-height: 100px;
}
</style>
</head>
<body>
<div id="myDivUI">Click Here</div>
<script>
const myDivUIElem = document.getElementById("myDivUI");
function updateBackgroundColor_ui() {
if (document.hasFocus()) {
myDivUIElem.style.backgroundColor = "lightgreen";
} else {
myDivUIElem.style.backgroundColor = "lightblue";
}
}
document.addEventListener("focus", updateBackgroundColor_ui);
document.addEventListener("blur", updateBackgroundColor_ui);
</script>
</body>
</html>
Instructions:
- Open the HTML page in a browser.
- Initially, the div’s background color is light blue.
- Click inside the browser window to give focus to the document. The div’s background color will change to light green.
- Click outside the browser window to move focus away from the document. The div’s background color will change back to light blue.
Dynamic Game Control
This example illustrates how to manage game state depending on whether the game canvas has focus, which is useful to control the game when window/tab focus changes. First, let’s create simple ball to move on the canvas, and then stop the animation when it looses the focus.
<!DOCTYPE html>
<html>
<head>
<title>Canvas Game Control</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
#gameCanvas {
border: 2px solid #333;
background-color: #fff;
}
#instructions {
margin-top: 20px;
padding: 10px;
border: 1px solid #ccc;
background-color: #eef;
text-align: center;
max-width: 600px;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="500" height="300"></canvas>
<div id="instructions">
<p>Click on the canvas to focus. The ball will move when focused.</p>
<p>Click outside to blur. The ball will stop when blurred.</p>
</div>
<script>
const canvas_game = document.getElementById("gameCanvas");
const ctx_game = canvas_game.getContext("2d");
let ballX = 50;
let ballY = 50;
let dx = 2;
let dy = 1;
let animationFrameId;
function drawBall() {
ctx_game.clearRect(0, 0, canvas_game.width, canvas_game.height);
ctx_game.beginPath();
ctx_game.arc(ballX, ballY, 20, 0, Math.PI * 2);
ctx_game.fillStyle = "blue";
ctx_game.fill();
ctx_game.closePath();
}
function updateBallPosition() {
ballX += dx;
ballY += dy;
if (ballX + 20 > canvas_game.width || ballX - 20 < 0) {
dx = -dx;
}
if (ballY + 20 > canvas_game.height || ballY - 20 < 0) {
dy = -dy;
}
}
function gameLoop() {
drawBall();
updateBallPosition();
animationFrameId = requestAnimationFrame(gameLoop);
}
function startGame() {
if (!animationFrameId) {
gameLoop();
}
}
function stopGame() {
if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
animationFrameId = null;
}
}
function checkFocus_game() {
if (document.hasFocus()) {
startGame();
} else {
stopGame();
}
}
document.addEventListener("focus", checkFocus_game);
document.addEventListener("blur", checkFocus_game);
// Initial check in case the page loads in focus
checkFocus_game();
</script>
</body>
</html>
Instructions:
- Open the HTML page in a browser.
- Initially, the ball does not move.
- Click on the canvas to focus. The ball will start moving.
- Click outside the browser window to move focus away from the document. The ball will stop moving.
- Click back inside the browser window to give focus to the document. The ball will start moving again.
Notes
- The
document.hasFocus()
method checks the focus state of the entire document. - Focus can be on any element within the document, such as input fields, buttons, or the document itself.
- The
focus
andblur
events are useful for detecting when the document gains or loses focus.
Browser Support
The document.hasFocus()
method is supported by all major browsers, including:
- Chrome
- Firefox
- Safari
- Edge
- Opera
Conclusion
The document.hasFocus()
method is a valuable tool for creating interactive and responsive web applications. By understanding how to use this method, you can create features that adapt to the user’s focus and provide a better user experience. Whether you’re building games, video players, or complex web applications, document.hasFocus()
can help you create more engaging and user-friendly experiences. 🎉