-
-
Save rodneyrehm/5901209 to your computer and use it in GitHub Desktop.
Maintain Focus on elements within a given element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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