Get the Currently Focused Element in JavaScript

04/10/2023

Contents

In this article, you will learn how to get the currently focused element in JavaScript.

Getting the currently focused element in JavaScript

In JavaScript, you can get the currently focused element on a web page using the document.activeElement property. This property returns the element that currently has the focus, which can be useful for interacting with user input or performing actions based on the currently selected element.

Here is an example of how to use the document.activeElement property:

const focusedElement = document.activeElement;

if (focusedElement.tagName === 'INPUT') {
  console.log('The focused element is an input field.');
} else if (focusedElement.tagName === 'BUTTON') {
  console.log('The focused element is a button.');
} else {
  console.log('The focused element is not an input or button.');
}

In this example, we first retrieve the currently focused element using the document.activeElement property. We then check the tagName property of the focused element to determine if it is an INPUT element or a BUTTON element. If the focused element is not an INPUT or BUTTON, we log a message indicating that the element is neither of these types.

You can also use the focus event to perform actions when an element gains focus, and the blur event to perform actions when an element loses focus. Here is an example of how to use the focus and blur events to change the background color of an element when it gains or loses focus:

<input type="text" id="myInput">

<script>
const myInput = document.getElementById('myInput');

myInput.addEventListener('focus', function() {
  myInput.style.backgroundColor = 'yellow';
});

myInput.addEventListener('blur', function() {
  myInput.style.backgroundColor = 'white';
});
</script>

In this example, we first retrieve the input element using its id attribute. We then add event listeners for the focus and blur events. When the focus event is fired, we change the background color of the input element to yellow. When the blur event is fired, we change the background color back to white.