I'm working with Twitter Bootstrap at the moment, and I'm encountering a strange problem in the tabindex of a modal:
I'm trying to tab through the form elements inside the modal, but after the last button the focus disappeared before coming back to the close button. I added a line in console that logs which element is being focused, and it turned out to be the modal itself, even though it has tabindex="-1"
.
I'm unable to share my code, but a quick look at the Bootstrap docs told me that it also happens in their example modal. The problem is reproducable:
Putting this in console will log whenever the modal (or in fact any element with tabindex="-1"
) gains focus.
$('[tabindex="-1"]').focus(function(){
console.log('Focus is on an element with negative tabindex')
});
(It also logs it when you click on the modal obviously, but that's out of scope).
Why does this happen? How can I prevent this? Is this a browser bug, a bug/feature of Twitter Bootstrap, or something else entirely?
tab, shift + tab and enter key and focus should be trapped inside modal and should not go out after pressing tab key multiple times.
A negative value (usually tabindex="-1" ) means that the element is not reachable via sequential keyboard navigation, but could be focused with JavaScript or visually by clicking with the mouse. It's mostly useful to create accessible widgets with JavaScript.
Thanks to Trevor. This is my final code:
$('.modal').keydown(function(e){
var $focusable = $(this).find("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])");
if($focusable.last().is(":focus") && !e.shiftKey && e.key == "Tab"){
e.preventDefault();
$focusable.first().focus();
}
else
if($focusable.first().is(":focus") && e.shiftKey && e.key == "Tab"){
e.preventDefault();
$focusable.last().focus();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With