Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable tab key focusing while Bootstrap modal is active

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?

like image 785
clxe Avatar asked Feb 13 '23 08:02

clxe


1 Answers

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');
});};
like image 72
Daryl Avatar answered Feb 14 '23 20:02

Daryl