How to Change the Active (Focused) Element in JavaScript
In web development, "focus" refers to the element on the page that is currently selected to receive keyboard input. Managing focus is crucial for creating accessible and user-friendly interfaces, especially in forms and dynamic applications. The standard way to programmatically change the active element is with the .focus() method.
This guide will teach you how to set focus on an element, how to handle elements that are not natively focusable, and how to remove focus from the currently active element.
The Core Concept: document.activeElement and element.focus()
JavaScript provides two key tools for managing focus:
document.activeElement: This is a read-only property that returns theElementthat currently has focus. If no element is focused, it typically returns the<body>element.element.focus(): This is a method that can be called on a focusable element to programmatically set focus to it.
How to Set Focus on an Element
You can call the .focus() method on any element that is natively focusable. This includes interactive elements like:
<input><select><textarea><button><a href="...">
For example, you want to set the focus to a specific input field when a page loads.
<input id="first-name" type="text">
<input id="last-name" type="text">
Solution:
// Get a reference to the element
const lastNameInput = document.getElementById('last-name');
// Call the .focus() method on it
lastNameInput.focus();
// Verify that it is now the active element
console.log(document.activeElement === lastNameInput);
// Output: true
How to Focus Non-Focusable Elements (like a <div>)
By default, non-interactive elements like <div>, <span>, or <p> cannot receive focus. Attempting to call .focus() on them will do nothing.
Example of code that does not work:
// ⛔️ This will not work by default.
document.getElementById('my-div').focus();
The solution is to make an element programmatically focusable, you must set its tabindex attribute.
tabindex="-1": Makes the element focusable via JavaScript (.focus()) but excludes it from the natural keyboard navigation order (Tab key). This is usually what you want.tabindex="0": Makes the element focusable and includes it in the natural keyboard navigation order.
const myDiv = document.getElementById('my-div');
// 1. Make the div programmatically focusable
myDiv.tabIndex = -1;
// 2. Now the focus() call will work
myDiv.focus();
// Add an outline to make the focus visible
myDiv.style.outline = '2px solid blue';
By default, a focused <div> has no visual indicator. It's a best practice to add a CSS :focus style (like an outline) to make it clear to the user which element is active.
How to Remove Focus from an Element (.blur())
The .blur() method is the opposite of .focus(). It removes keyboard focus from the element it is called on. If you call it on the document.activeElement, you can effectively "unfocus" whatever is currently selected.
Solution:
// Get a reference to the currently focused element
const currentlyFocused = document.activeElement;
if (currentlyFocused) {
// Remove focus from that element
currentlyFocused.blur();
}
// After .blur(), the focus typically returns to the <body>
console.log(document.activeElement === document.body);
// Output: true
Practical Example: Setting Focus on an Input After a Button Click
A common UI pattern is to click a button that reveals an input field and immediately sets focus to it, so the user can start typing without an extra click.
HTML:
<button id="show-input-btn">Enter Your Name</button>
<input id="name-input" type="text" style="display: none;">
JavaScript:
const showButton = document.getElementById('show-input-btn');
const nameInput = document.getElementById('name-input');
showButton.addEventListener('click', () => {
// 1. Hide the button and show the input
showButton.style.display = 'none';
nameInput.style.display = 'block';
// 2. Set focus on the newly visible input field
nameInput.focus();
});
Conclusion
Programmatically managing focus is an essential skill for creating accessible and intuitive web applications.
- To set focus on a focusable element, use the
element.focus()method. - To make a non-focusable element (like a
<div>) able to receive focus, set itstabIndexproperty to-1. - To remove focus from the currently active element, use
document.activeElement.blur().
By using these simple methods, you can guide your users and create a smoother, more keyboard-friendly experience.