Created
September 3, 2016 18:09
-
-
Save motss/081be5736bc830a1cb09d5fe6c30c1c7 to your computer and use it in GitHub Desktop.
trap focus within modal dialog
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
_trapFocusWithinModal (ev, focusableNodes, callback) { | |
const _kc = ev.keyCode; | |
if (ev.type === 'keydown' && _kc === TAB_KEY) { | |
console.log('keyboard tab on:', ev.target, focusableNodes); | |
// Prevent default TAB operation. | |
ev.preventDefault(); | |
const _maxAllowableFocusableNodesLength = focusableNodes.length - 1; | |
const _oldFocusingTarget = ev.target; | |
const _oldFocusingTargetIdx = focusableNodes.findIndex(el => el.isEqualNode(_oldFocusingTarget)); | |
let _nextFocusingTargetIdx = _oldFocusingTargetIdx + 1; | |
if (_nextFocusingTargetIdx > _maxAllowableFocusableNodesLength) { | |
_nextFocusingTargetIdx = 0; | |
} | |
const _nextFocusingTarget = focusableNodes[_nextFocusingTargetIdx]; | |
// Save document.activeElement before focusing the next target. | |
this._activeNodeWhenModalOpened = _nextFocusingTarget; | |
// Focus active node on next frame. | |
window.requestAnimationFrame(_ => this._activeNodeWhenModalOpened.focus()); | |
}else if (_kc === ENTER_KEY || _kc === SPACE_KEY) { | |
console.log('why-you-no-run-callback-in-focus-trap-method', callback, ev); | |
callback(ev); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment