Skip to content Skip to sidebar Skip to footer

How To Stop Tab Key Event From Firing When A Modal Is Open

When the modal is showing, how can I disable key events like TAB? I have multiple buttons and fields in a form on the page that can be selected (focused) by tabbing. I want to disa

Solution 1:

You can add your own event listener:

// Your event listenerfunctionpreventTab(e) {
  e = e || window.event;
  if (e.keyCode === 9) { // If tab key is pressed
    e.preventDefault() // Stop event from its action
  }
}

// Call this when modal window opensdocument.addEventListener(preventTab);

// Call this when modal window closes/unmountsdocument.removeEventListener(preventTab);

Solution 2:

I'd suggest something like this - use Renderer2 and listen for a keydown event and filter events by keyCode. Then on modal hide remove that listener.

onShow() {
   this.removeTabKeyListener = this.renderer.listen('document', 'keydown', (event) => {
      if (event.keyCode === 9) { 
        event.preventDefault();
      }
    });
}

onHide() {
  this.removeTabKeyListener();
}

A little example - http://plnkr.co/edit/LdpmCpgapPbrA26fGO9U?p=preview

Solution 3:

You can disable tab by preventDafault the keyCode 9 (tab) on keydow:

$(document).keydown(function(e) {
    if (e.keyCode == 9) {
        e.preventDefault();
    }
});

Of course you'll want that on your modal opener and not as is, so it won't permanently disable tabs ;)

Solution 4:

Try this code it will just disable your tab key when modal is showing.

 $(document).keydown(function(e){
    if (e.which==9) // keycode for tab key
    {
        checkmodal = $('#myModal').is(':visible'); //check modal is opened or notif (checkmodal){
            e.preventDefault();
        }
    }
});

Post a Comment for "How To Stop Tab Key Event From Firing When A Modal Is Open"