jqueryjquery-uijquery-tools

How does jQuery UI Dialog disable focus on background inputs?


When you open a modal dialog using jQuery UI, you'll notice that if you use the Tab key, you can focus on the dialog's buttons, but any inputs outside the dialog are ignored. I'm trying to achieve this same behavior with jQuery UI Tools Overlay , but I'm not sure how jQuery UI is doing it. It doesn't seem to be setting the elements' tab index to -1, and besides, doing this would be extremely tedious since it would involve finding all the focusable elements that aren't part of the dialog. This wouldn't be very good if you require automation. Is there a way to disable focus an all of the page's elements except a few?


Solution

  • The dialog widget actually handles the keypress event and performs its own Tab key processing. This processing ignores tabbable elements outside of the dialog.

    The relevant source code (lines 286 to 305 in the current version at the time of this post) is:

    // prevent tabbing out of modal dialogs
    if (options.modal) {
        uiDialog.bind('keypress.ui-dialog', function(event) {
            if (event.keyCode !== $.ui.keyCode.TAB) {
                return;
            }
    
            var tabbables = $(':tabbable', this),
                first = tabbables.filter(':first'),
                last  = tabbables.filter(':last');
    
            if (event.target === last[0] && !event.shiftKey) {
                first.focus(1);
                return false;
            } else if (event.target === first[0] && event.shiftKey) {
                last.focus(1);
                return false;
            }
        });
    }
    

    Note that TrueBlueAussie's comment is right, and that release of the dialog widget used to bind to the wrong event. keydown should be used instead of keypress:

    uiDialog.bind('keydown.ui-dialog', function(event) {
        // ...
    });