Avoid Accessibility Warnings in Bootstrap Modals with a Simple blur()
Fix
you may have seen a browser warning like this:
“Blocked aria-hidden on an element because its descendant retained focus.”
This message usually appears when you’re hiding a modal that still has a focused element inside—often an <input>
or a <button>
. It might not break your interface visually, but it does signal a problem with accessibility and assistive technologies.
The Problem
When Bootstrap hides a modal, it sets aria-hidden="true"
on the modal container. If any element inside that modal still has focus (like a text field or submit button), it violates accessibility standards:
- Screen readers may still try to interact with the now-hidden element.
- Some browsers will throw a warning to alert developers about this mismatch.
- It may confuse keyboard users or users relying on assistive technology.
The Fix: blur()
Before Hiding
To prevent this issue, you just need to remove focus from any element inside the modal before it’s hidden. That’s where document.activeElement.blur()
comes in.
Here’s a simple and scalable way to do it:
document.querySelectorAll('.modal').forEach((modal) => {
modal.addEventListener('hide.bs.modal', () => {
document.activeElement.blur();
});
});
This will:
- Listen for the Bootstrap
hide.bs.modal
event. - Blur the currently focused element if it’s inside the modal.
- Prevent the browser from complaining about
aria-hidden
+ focused conflicts.
Why This Should Be in Your JS File
Including this small snippet in your JavaScript setup ensures:
- Accessibility compliance — No focused elements are hidden from assistive tech.
- No console warnings — Your app stays clean in the browser devtools.
- Cleaner UX — Focus is safely removed without abrupt shifts or weird tab behavior.
- Scalability — Automatically applies to every modal on the page without needing to manually handle each one.
@martin, this could be a nice addition to bs-init.js
.