Modal focus on close #41097
-
It appears Bootstrap's modal nicely shifts focus from the closed modal back to the or that triggered it. So I understand focus will be returned easily for this implementation:
But if we're implementing a modal like this?
Is there a promise made that Bootstrap will get focus back to #exampleModalTrigger? Or does it only work with data attributes? Or will it work if I go the vanilla JS route? Or is it meant to work with all of these tactics and there's something else about my implementation that I need to troubleshoot? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
When Lines 352 to 356 in a353ed4 When you don't use The code could be improved, but basically, it can be done like this: (() => {
'use strict';
const btnSecondary = document.getElementById('btnSecondary');
const exampleModal = document.getElementById('exampleModal');
const myModal = new bootstrap.Modal(exampleModal, {});
btnSecondary.addEventListener('click', (event) => {
if (myModal) {
exampleModal.addEventListener('hidden.bs.modal', (event) => {
btnSecondary.focus();
});
myModal.show();
}
});
})(); The idea here is to listen to the In jQuery, could be something like this (haven't tested): $('#exampleModal').on('hidden.bs.modal', function () {
$('#btnSecondary').focus();
}); |
Beta Was this translation helpful? Give feedback.
When
data-bs-toggle="modal"
is used, the code automatically gives back the focus to the element that triggered the modal. It's done in our code atbootstrap/js/src/modal.js
Lines 352 to 356 in a353ed4
When you don't use
data-bs
, you'll have to do that manually. I've created a StackBlitz showing how to give back the focus in JS.The code could be improved, but basically, it can be done like this: