How to Handle Focus and Blur Events in JavaScript
focus and blur event listeners on elements to detect when they gain or lose focus. Attach handlers with addEventListener and ensure the element is focusable (like input or button). Use focusin and focusout for event bubbling if needed.Why This Happens
Developers often try to handle focus and blur events but find their handlers not firing as expected. This usually happens because focus and blur do not bubble up the DOM tree, so attaching listeners to parent elements won't work. Also, some elements are not focusable by default, so events never trigger.
const container = document.getElementById('container'); container.addEventListener('focus', () => { console.log('Focused container'); }, true); // HTML // <div id="container"> // <input type="text" /> // </div>
The Fix
Attach focus and blur event listeners directly to the focusable elements like input or button. Alternatively, use focusin and focusout events on parent elements because they bubble. Also, ensure elements can receive focus by using tabindex if needed.
const container = document.getElementById('container'); // Using focusin which bubbles container.addEventListener('focusin', (event) => { console.log('Focused element:', event.target); }); container.addEventListener('focusout', (event) => { console.log('Blurred element:', event.target); }); // HTML // <div id="container"> // <input type="text" /> // <button>Click me</button> // </div>
Prevention
Always attach focus and blur listeners directly to elements that can receive focus. Use focusin and focusout on containers if you want to handle events from multiple children. Make sure elements are focusable by default or add tabindex="0". Test your event handlers in different browsers to ensure consistent behavior.
Related Errors
Common related issues include:
- Handlers not firing because events don’t bubble (
focusvsfocusin). - Trying to focus non-focusable elements without
tabindex. - Using inline
onfocusoronblurattributes which can be less flexible.