0
0
JavascriptDebug / FixBeginner · 4 min read

How to Handle Focus and Blur Events in JavaScript

Use the 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.

javascript
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.

javascript
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>
Output
Focused element: [input element] Blurred element: [input element]
🛡️

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 (focus vs focusin).
  • Trying to focus non-focusable elements without tabindex.
  • Using inline onfocus or onblur attributes which can be less flexible.

Key Takeaways

Attach focus and blur listeners directly to focusable elements or use focusin/focusout for bubbling.
Ensure elements are focusable by default or add tabindex="0" to make them focusable.
Remember that focus and blur events do not bubble, but focusin and focusout do.
Test event handling across browsers for consistent behavior.
Avoid inline event handlers for better control and maintainability.