Skip to content

Instantly share code, notes, and snippets.

@drublic
Last active March 29, 2017 15:20
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save drublic/5899658 to your computer and use it in GitHub Desktop.
Save drublic/5899658 to your computer and use it in GitHub Desktop.
A function that lets you circularly tab through a part of a page.
var tabbableElements = 'a[href], area[href], input:not([disabled]),' +
'select:not([disabled]), textarea:not([disabled]),' +
'button:not([disabled]), iframe, object, embed, *[tabindex],' +
'*[contenteditable]';
var keepFocus = function (context) {
var allTabbableElements = context.querySelectorAll(tabbableElements);
var firstTabbableElement = allTabbableElements[0];
var lastTabbableElement = allTabbableElements[allTabbableElements.length - 1];
var keyListener = function (event) {
var keyCode = event.which || event.keyCode; // Get the current keycode
// Polyfill to prevent the default behavior of events
event.preventDefault = event.preventDefault || function () {
event.returnValue = false;
};
// If it is TAB
if (keyCode === 9) {
// Move focus to first element that can be tabbed if Shift isn't used
if (event.target === lastTabbableElement && !event.shiftKey) {
event.preventDefault();
firstTabbableElement.focus();
// Move focus to last element that can be tabbed if Shift is used
} else if (event.target === firstTabbableElement && event.shiftKey) {
event.preventDefault();
lastTabbableElement.focus();
}
}
};
context.addEventListener('keydown', keyListener, false);
};
// Call the function when the part of the page gets focus
var modal = document.querySelector('.modal');
keepFocus(modal);
modal.focus();
@kbav
Copy link

kbav commented Jul 11, 2013

For reference... the theory & how-to behind this code can be found here: http://drublic.de/blog/accessible-dialogs-modals/

Thanks, @drublic!

@realalexhomer
Copy link

Hey guys, I've been working on an accessibility project for a client, and I used the idea in your blog to what I think is a nice effect. You can see the version I made here (dependant on jquery).

https://gist.github.com/realalexhomer/cd3d816fd6e5b1d28211

It's nice because it take into account the possibility of elements being hidden, and doesn't make the mistake of tabbing over them. Another difference is that it lets you specify which elements to include in your markup.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment