Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict Tab Key in the modal box?

I have a modal window that pops up when you click a .btn link.

When it is active, users can still press Tab to focus on links and buttons in the background, some of which have download links. When these links are focused on and user pressed enter key the download action takeplace.

Is there a way to disable background Tab while the modal window is active?

I am using below versions:

https://valor-software.com/ngx-bootstrap/#/modals (V2.4), Angular CLI 1.6

like image 450
svs Avatar asked Nov 20 '25 04:11

svs


1 Answers

Since the latest ngx-bootstrap(v2.4) does not have the fix, I created a directive to trap tab key focus in the modal box itself.

Angular Version I used is, Angular 5

My directive is below.

Directive

import {Directive, ElementRef, HostListener} from '@angular/core';
@Directive({
    selector: '[appSdbModalFocus]'
})
export class SdbModalFocusDirective {
    KEYCODE_TAB: number = 9;

    constructor(
        private hostElement: ElementRef
    ) {}

    ngOnInit() {}

    @HostListener("keydown", ["$event"])
    onKeyDown(e: KeyboardEvent): any {
        if (e.key === 'Tab' || e.keyCode === this.KEYCODE_TAB) {
            let focusableEls = this.hostElement.nativeElement;
            let modalContent = $(focusableEls).find('a, :input, [tabindex]');
            var firstFocusableEl = modalContent.first()[0];
            var lastFocusableEl = modalContent.last()[0];

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

HTML

<form appSdbModalFocus>
...
</form>

Created this directive with the help of trap-focus-in-an-element

like image 75
svs Avatar answered Nov 24 '25 06:11

svs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!