Focus trap improvements

This commit is contained in:
Sam Potts
2020-02-09 21:42:12 +00:00
parent 74ba6a96fc
commit 2d13ad3d39
2 changed files with 99 additions and 109 deletions

View File

@ -2,7 +2,6 @@
// Element utils
// ==========================================================================
import { toggleListener } from './events';
import is from './is';
import { extend } from './objects';
@ -248,40 +247,6 @@ export function getElement(selector) {
return this.elements.container.querySelector(selector);
}
// Trap focus inside container
export function trapFocus(element = null, toggle = false) {
if (!is.element(element)) {
return;
}
const focusable = getElements.call(this, 'button:not(:disabled), input:not(:disabled), [tabindex]');
const first = focusable[0];
const last = focusable[focusable.length - 1];
const player = this;
const trap = event => {
// Bail if not tab key or not fullscreen
if (event.key !== 'Tab' || event.keyCode !== 9 || !player.fullscreen.active) {
return;
}
// Get the current focused element
const focused = document.activeElement;
if (focused === last && !event.shiftKey) {
// Move focus to first element that can be tabbed if Shift isn't used
first.focus();
event.preventDefault();
} else if (focused === first && event.shiftKey) {
// Move focus to last element that can be tabbed if Shift is used
last.focus();
event.preventDefault();
}
};
toggleListener.call(this, this.elements.container, 'keydown', trap, toggle, false);
}
// Set focus and tab focus class
export function setFocus(element = null, tabFocus = false) {
if (!is.element(element)) {