Marley Marley - 1 year ago 147
HTML Question

How to lock the tab focus on a modal in typescript?

I have a bootstrap modal with two button elements. When the modal is opened, the buttons get the focus but when I tab twice, the focus leaves the modal and goes to some other element on the main screen.

So, my question is how to lock the tab focus on the modal, i.e., tabbing on the first button, the focus should go to the next button, and tabbing on the second button should get back the focus onto the first button.

I have seen the similar query in other questions where they were asking to use ids to the tags which I don't want to implement.

The following is the modal:

<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Are you sure?</h4>
<div class="modal-body">
<div class="modal-footer ok-cancel">
<button type="button" class="btn btn-primary" (click)="delete()" data-dismiss="modal">Delete</button>
<button type="button" class="btn btn-default" (click)="cancel()">Cancel</button>

And also, I might have more modals in future where I could have more elements on the modal. In that case, how could I achieve this?

PS: I am implementing this in an Angular2 framework with typescript.

Answer Source

You can implement the following method:

private tabKey(event: KeyboardEvent) {
        let parentModal = $(document).find('.modal');
        //List of html elements which can be focused by tabbing.
        let focusableElementsArrayString = 'a[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex="0"]';
        let focusableElementsInModal = parentModal.find(focusableElementsArrayString);
        let numberOfElements = focusableElementsInModal.length;
        let firstTabElement = focusableElementsInModal[0];
        let lastTabElement = focusableElementsInModal[numberOfElements - 1];
        // Check for Shift + Tab
        if (event.keyCode === 9 && event.shiftKey) {
            if (document.activeElement === firstTabElement) {
            } // Check for Tab
        } else if (event.keyCode === 9) {
            if (document.activeElement === lastTabElement) {

I have even implemented the shift+tab for you in the code. Hope that helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download