JAVASCRIPT
Managing Element Focus Programmatically in JavaScript
Learn to control keyboard focus on DOM elements using `focus()` and `blur()` methods, enhancing accessibility and user experience in interactive forms and dynamic UI components.
// HTML Structure example:
// <input type="text" id="myInput" placeholder="Enter text...">
// <button id="focusButton">Set Focus</button>
// <button id="blurButton">Remove Focus</button>
// <button id="autoFocusBtn">Auto Focus Input after 2s</button>
const myInput = document.getElementById('myInput');
const focusButton = document.getElementById('focusButton');
const blurButton = document.getElementById('blurButton');
const autoFocusBtn = document.getElementById('autoFocusBtn');
// Set focus to the input when 'Set Focus' button is clicked
focusButton.addEventListener('click', function() {
myInput.focus();
console.log('Input focused.');
});
// Remove focus from the input when 'Remove Focus' button is clicked
blurButton.addEventListener('click', function() {
myInput.blur();
console.log('Input blurred.');
});
// Example: Auto-focus after a delay (e.g., after loading data or showing a modal)
autoFocusBtn.addEventListener('click', function() {
console.log('Will focus input in 2 seconds...');
setTimeout(() => {
myInput.focus();
console.log('Input automatically focused after delay.');
}, 2000);
});
How it works: Programmatic focus management is crucial for accessibility and user experience, especially in single-page applications or dynamic forms. The `focus()` method sets the keyboard focus on a specific element, making it the active element that receives keyboard input. Conversely, the `blur()` method removes focus from an element. These methods are essential for guiding user interaction, such as automatically focusing an input field in a modal, or after a specific action is completed, improving navigation for keyboard users.