Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@expertsuggestion
Created December 11, 2022 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save expertsuggestion/a8c5691236f40222293ecb263d8899bb to your computer and use it in GitHub Desktop.
Save expertsuggestion/a8c5691236f40222293ecb263d8899bb to your computer and use it in GitHub Desktop.
Trap Focus Inside Particular Area In Angular by Exclude the Hidden, Disabled & display none elements
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) {
const focusableEls1 = element.querySelectorAll(
'a[href], button, textarea, input[type="text"], input[type="radio"], input[type="checkbox"], select, [tabindex]:not([tabindex="-1"]'
);
let focusableEls = [].filter.call(focusableEls1, function (el: any) {
var style = window.getComputedStyle(el);
return style.display !== 'none' && !el.disabled;
});
console.log('focusableEls', focusableEls);
const firstFocusableEl: any = focusableEls[0];
const lastFocusableEl: any = focusableEls[focusableEls.length - 1];
element.addEventListener('keydown', function (e) {
var isTabPressed = e.keyCode === 9; // isTabPressed
if (!isTabPressed) return;
if (e.shiftKey) {
/* shift + tab */ if (document.activeElement === firstFocusableEl) {
lastFocusableEl.focus();
e.preventDefault();
}
} /* tab */ else {
if (document.activeElement === lastFocusableEl) {
firstFocusableEl.focus();
e.preventDefault();
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment