Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 552
JayPea Avatar asked Oct 17 '12 14:10

JayPea


2 Answers

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) {
    // ...
});
like image 105
Frédéric Hamidi Avatar answered Sep 22 '22 10:09

Frédéric Hamidi


Here's the chunk of code that handles this:

// prevent tabbing out of modal dialogs
this._on(uiDialog, {
    keydown: function(event) {
        if (!options.modal || event.keyCode !== $.ui.keyCode.TAB) {
            return;
        }
        var tabbables = $(":tabbable", uiDialog),
            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;
        }
    }
});​

It looks like jQuery UI adds a filter (:tabbable) to the jQuery selector engine and when the dialog is active, it only allows the tab to cycle between the modal's tabbable elments.

Code from: https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.dialog.js

like image 38
j08691 Avatar answered Sep 21 '22 10:09

j08691