Situation:
I have a webpage which opens modal windows (light boxes) which contain forms where the user can input data. Users generally navigate using the keyboard, tabbing from one field to the next.
Problem:
When a modal window opens, only the window is active, the rest of the page is not accessible using the mouse, but elements can be reached by tabbing out of the modal window.
Question:
How can I restrict movement by using the tab button to only the elements within the form window?
The only thing I can think of is using Javascript to set tabindex=-1
on all form elements (and other focusable elements) when the modal window is opened and then set the tabindex
values back to their previous values when the modal window is closed.
Is there a simpler/better way?
Have a look at the jQuery BlockUI Plugin. They have an example using a modal box with two buttons, and it restricts tabbing as well.
It may or may not work out-of-the-box with your modal windows, but it's worth a look instead of having to implement your own work-around.
No, it's the only way.
tabIndex
greater than-1
† and don't belong to your modal.tabIndex
.tabIndex
to-1
so it can no longer receive focus from the keyboard.tabIndex
.Here's a quick demo:
† We look for
tabIndex > -1
so that we can focus specifically on tabable elements. You could further restrict that filter to ignore hidden elements, but I'll leave that to you. In either case, the list shouldn't be very big.‡ Alternatively, as in the demo, you could fill the array with a series of functions whose sole purpose is to reset
tabIndex
. You could also forego the array entirely and simply add adata-original-tab-index
attribute to the affected elements... usingdocument.querySelectorAll("[data-original-tab-index]")
to retrieve them after the fact.Here's a demo which uses data attributes to store the original
tabIndex
so you don't have to maintain your own array:See
HTMLElement.dataset
How about catching the
tab-key
? On the last element and then put the focus on the first and vice versa withshift-tab
This I am using in a multi-modless-diaolog environment, to keep the focus with in a Dialog, switching between dialogs with mouse or other key
small edit: replaced my on "unibind()" (=.off(x).on(x)) function through jQuery "on()"
Even though it is an old post I was looking for a solution to this problem and did the following to solve it.
Using JQuery I disabled all input fields in different forms and divs as soon as the modal window opens up (except the ones on the modal form itself).
$('#formId :input').prop('disabled',true);
when the modal form is closed, you can enable the input elements again.
Disabled fields are not considered when "tabbing" around your page.
in case you want to restrict the focus inside dom "parent"
supported by all mordern browsers