Focus Trap page

TypeScript - FocusTrapModule.ts

            

export class FocusTrapModule {
	constructor(element) {
		this.trapFocus(element);
	}

	private trapFocus(element: HTMLElement) {
		const focusableEls = element.querySelectorAll('a[href]:not([disabled]), button:not([disabled]), textarea:not([disabled]), input[type="text"]:not([disabled]), input[type="radio"]:not([disabled]), input[type="checkbox"]:not([disabled]), select:not([disabled]), div[tabindex="0"]');
		const KEYCODE_TAB = 9;

		for (let i = 0; i < focusableEls.length; i++) {
			const firstFocusableEl = focusableEls[0];
			const lastFocusableEl = focusableEls[focusableEls.length - 1];

			firstFocusableEl.focus();

			element.addEventListener('keydown', (e: any) => {
				const isTabPressed = (e.key === 'Tab' || e.keyCode === KEYCODE_TAB);

				if (!isTabPressed) {
					return;
				}

				if (e.shiftKey) /* shift + tab */ {
					if (document.activeElement === firstFocusableEl) {
						lastFocusableEl.focus();
						e.preventDefault();
					}
				}
				else /* tab */ {
					if (document.activeElement === lastFocusableEl) {
						firstFocusableEl.focus();
						e.preventDefault();
					}
				}
			});
		}
	}
}