Skip to content

Instantly share code, notes, and snippets.

@rodneyrehm
Forked from drublic/keep-focus.js
Last active December 19, 2015 04:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodneyrehm/5901209 to your computer and use it in GitHub Desktop.
Save rodneyrehm/5901209 to your computer and use it in GitHub Desktop.
Maintain Focus on elements within a given element
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 elements = context.querySelectorAll(tabbableElements);
var keyListener = function (event) {
var keyCode = event.which || event.keyCode;
if (keyCode !== 9) {
// not a TAB, ignore it...
return;
}
// late grab of first/last element identification, because
// DOM might have changed since registering this helper.
// remember that DOMNodeList is a live view of the query
// (unlike jQuery's static list)
var first = elements[0];
var last = elements[elements.length - 1];
if (event.target === last && !event.shiftKey) {
// loop around the end
first.focus();
} else if (event.target === first && event.shiftKey) {
// loop around the beginning
last.focus();
} else {
// ignore tabs in between
return;
}
// prevent browser from handling these TABs
event.preventDefault && event.preventDefault() || (event.returnValue = false);
event.stopPropagation && event.stopPropagation();
};
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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment