Detecting if an Element is Focused Using JavaScript

JavaScript provides a straightforward way to detect if an element is focused. In this article, we'll explore how to achieve this using JavaScript.

The "document.activeElement" Property

The document.activeElement property is a useful tool for determining which element is currently focused in the document.

It returns the currently focused element or null if no element has focus.

By comparing the active element with the element you're interested in, you can determine if the desired element is focused.

Let's create a simple function to check if a specific element is focused:

// Function to check if an element is focused
function isElementFocused(element) {
  return document.activeElement === element;
}

// Example usage
const myInput = document.getElementById('myInput');
console.log(isElementFocused(myInput)); // Returns true or false

In this code:

Example: Styling Focused Element

Let's create a complete example where we change the styling of an input field when it gains focus:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Element Focus Detection Example</title>
  <style>
    /* Styling for the focused input */
    #myInput:focus {
      border: 2px solid #4CAF50;
      background-color: #f0f0f0;
    }
  </style>
</head>
<body>

  <label for="myInput">Type something:</label>
  <input type="text" id="myInput" onfocus="handleFocus()" onblur="handleBlur()">

  <script>
    // Function to handle input focus
    function handleFocus() {
      const myInput = document.getElementById('myInput');
      console.log(`Input focused: ${isElementFocused(myInput)}`);
    }

    // Function to handle input blur
    function handleBlur() {
      const myInput = document.getElementById('myInput');
      console.log(`Input blurred: ${isElementFocused(myInput)}`);
    }

    // Function to check if an element is focused
    function isElementFocused(element) {
      return document.activeElement === element;
    }
  </script>
</body>
</html>

In this example:

Conclusion

Detecting whether an element is focused is a valuable capability in web development.

JavaScript, with the help of the document.activeElement property, allows you to determine the currently focused element and perform actions accordingly.

Use this knowledge to create more interactive and user-friendly web applications by responding to focus events on specific elements.