In Bootstrap 3, I have a modal window that pops up when you click a .btn
link.
When it is active, users can still press Tab to focus on links and buttons in the background, some of which have tooltips and such. When these links are focused on, their tooltips overlap the modal window, which looks kind of silly.
Is there a way to disable Tab while the modal window is active, and re-enable Tab when it closes?
This solution still allows the tab key to function as normal on any focusable elements within your modal. Just call it when your DOM has loaded and it'll work for any modal on your page.
disableTabModalShown = function () {
$('.modal').on('shown.bs.modal', function() {
var modal = $(this);
var focusableChildren = modal.find('a[href], a[data-dismiss], area[href], input, select, textarea, button, iframe, object, embed, *[tabindex], *[contenteditable]');
var numElements = focusableChildren.length;
var currentIndex = 0;
$(document.activeElement).blur();
var focus = function() {
var focusableElement = focusableChildren[currentIndex];
if (focusableElement)
focusableElement.focus();
};
var focusPrevious = function () {
currentIndex--;
if (currentIndex < 0)
currentIndex = numElements - 1;
focus();
return false;
};
var focusNext = function () {
currentIndex++;
if (currentIndex >= numElements)
currentIndex = 0;
focus();
return false;
};
$(document).on('keydown', function (e) {
if (e.keyCode == 9 && e.shiftKey) {
e.preventDefault();
focusPrevious();
}
else if (e.keyCode == 9) {
e.preventDefault();
focusNext();
}
});
$(this).focus();
});
$('.modal').on('hidden.bs.modal', function() {
$(document).unbind('keydown');
});};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With