JAVASCRIPT
Programmatically Focus on Any HTML Element
Enhance user experience and accessibility by learning how to programmatically set focus on specific input fields, buttons, or interactive elements using JavaScript's `focus()` method.
// Focus on an input field after page load or form submission
document.getElementById('myInputField').focus();
// Example: Focus on a button when another button is clicked
document.getElementById('triggerFocusButton').addEventListener('click', () => {
const targetButton = document.getElementById('confirmButton');
if (targetButton) {
targetButton.focus();
console.log('Focus moved to confirm button.');
}
});
// To prevent scrolling when focusing, use the options object (not supported everywhere yet)
// document.getElementById('anotherInputField').focus({ preventScroll: true });
How it works: The `focus()` method programmatically sets focus on a specified element, making it the active element in the document. This is crucial for improving accessibility (e.g., directing keyboard navigation), enhancing form usability (e.g., focusing on the first error field), or guiding user interaction in single-page applications. It simulates a user clicking or tabbing to the element.