Last active
August 8, 2021 18:52
-
-
Save thehaseebahmed/e20eaf974f7dd0b9071c80d52e5b8478 to your computer and use it in GitHub Desktop.
An angular directive that enables you to trap focus to a certain HTML element. You can read more about it here: http://bit.ly/how-to-trap-focus
This file contains hidden or 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
import { Directive, ElementRef, AfterViewInit } from '@angular/core'; | |
@Directive({ | |
selector: '[trapFocus]' | |
}) | |
export class TrapFocusDirective implements AfterViewInit { | |
constructor( | |
private el: ElementRef | |
) {} | |
ngAfterViewInit() { | |
this.trapFocus(this.el.nativeElement); | |
} | |
trapFocus(element) { | |
element.addEventListener('keydown', function(e) { | |
const getActiveElement = () => { | |
if (document.activeElement?.shadowRoot) { return document.activeElement.shadowRoot.activeElement; } | |
else { return document.activeElement; } | |
}; | |
const isTabPressed = e.keyCode === 9; // isTabPressed | |
if (!isTabPressed) return; | |
const focusableEls1 = element.querySelectorAll( | |
'a[href], button, textarea, input[type="text"],' + | |
'input[type="radio"], input[type="checkbox"], select' | |
); | |
const focusableEls = Array.from(focusableEls1).filter( (el: any) => !el.disabled); | |
const firstFocusableEl: any = focusableEls[0]; | |
const lastFocusableEl: any = focusableEls[focusableEls.length - 1]; | |
if ( e.shiftKey ) /* shift + tab */ { | |
if (getActiveElement() === firstFocusableEl) { | |
lastFocusableEl.focus(); | |
e.preventDefault(); | |
} | |
} else /* tab */ { | |
if (getActiveElement() === lastFocusableEl) { | |
firstFocusableEl.focus(); | |
e.preventDefault(); | |
} | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment