Restrict tabindex focusing to a section of the page

SlappyTheFish picture SlappyTheFish · Mar 5, 2011 · Viewed 10.9k times · Source

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?

Answer

halfbit picture halfbit · Jun 1, 2016

How about catching the tab-key? On the last element and then put the focus on the first and vice versa with shift-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

inputs=".editing, input, textarea, button, a, select"
no_tab="[type='hidden'], :disabled"

$focusable=dlg.$form.find(inputs).not(no_tab)


$fa_first=$focusable.first()
$fa_last=$focusable.last()

$fa_last.on("keydown", (evt) =>
    if evt.keyCode==9 && ! evt.shiftKey
        $fa_first.focus()
        evt.preventDefault()
        false
)
$fa_first.on("keydown", (evt) =>
    if evt.keyCode==9 && evt.shiftKey
        $fa_last.focus()
        evt.preventDefault()
        false
)

small edit: replaced my on "unibind()" (=.off(x).on(x)) function through jQuery "on()"