JavaScript's hasFocus() Method
The hasFocus() method in JavaScript is designed to check if an element on a web page currently has focus. This essentially means it determines whether a user is actively interacting with that element, for example, by typing into a text field.
hasFocus()
Belonging to the document object model, this method plays a crucial role in interactive web design.
It returns true if any element within the page is in focus. Otherwise, it returns false.
Practical Uses: It's incredibly useful for a variety of scenarios. Imagine you have a form on a web page; this method allows you to check if the user is currently filling out a particular field.
Let’s dive into a real-world example.
Consider a page with a text input field. I aim to display a notification whenever this field gains focus.
<!DOCTYPE html>
<html>
<body>
<input type="text" id="testo" placeholder="Click here and start typing...">
<p id="messaggio"></p>
<script>
// Function for focus verification
function verificaFocus() {
if (document.hasFocus() && document.getElementById("testo") === document.activeElement) {
document.getElementById("messaggio").innerHTML = "You're typing in the text field!";
} else {
document.getElementById("messaggio").innerHTML = "";
}
}
// Adding event listeners to the text field
document.getElementById("testo").addEventListener("focus", verificaFocus);
document.getElementById("testo").addEventListener("blur", verificaFocus);
</script>
</body>
</html>
This setup includes an input field and a paragraph for displaying messages.
A function named verificaFocus() has been crafted to check for two key conditions: whether the page is focused and if the element is the active one. If both conditions are met, a message is displayed. Otherwise, the message is cleared.
The example effectively utilizes document.activeElement to identify which element currently has focus.
If it's the input field, this confirms that the user is engaging with it.
Note: The hasFocus() method merely indicates the presence of focus within the page but does not specify the element. Hence, document.activeElement becomes essential for pinpointing the focused element.
This approach achieves the intended effect seamlessly. Here’s the functionality in action on the webpage.