Disabling Tab with JavaScript

Occasionally when building web applications, the need arises to stop event propagation and/or event bubbling (for more information, check out this page).

I’ve been working on a control that sits above all of the other elements of the page and must maintain focus of the mouse and keyboard while it is being displayed. In order to do this, I needed to prevent the default behavior of the Tab key whenever this control was visible on the screen. Without going into too many details, I’ll just add that I’m needing to override this behavior in order to make sure the user interacts with the control and cannot bypass it - ultimately, it’s a security measure and it’s for their own good.

Before continuing, I’d like to add that I’m not really a fan of overriding behavior like this. From a usability standpoint, it contradicts what the user thinks will happen when they perform an action versus what will happen. As such, it breaks their conceptual model of how they believe the thing work. Knowing that I’m doing all of this makes me feel lame. Regardless, it’s for their own good. The ends justify the means.

With that said, the major browsers name their event object differently, so you need to get a reference to that object before capturing the event. Next, we only want to stop the default behavior based on the Tab key (which has the keycode of 9). Here’s how to do it such that it works in IE, Safari, and Firefox:

document.onkeydown = DisableTab;
function DisableTab(evt) {

var evt = (evt) ? evt : ((event) ? event : null);
if(evt.keycode == 9) {

return false;

}

}

Again, this is one of those solutions that I’m not really a fan of, but is needed. Many of the alternatives that I found when looking around didn’t work correctly across the major browsers so I ended up doing it this way and it worked.

Update: Please see comments for additional fixes with respect to Firefox 3 and Mac OSX. Thanks to Tom for the comment.


 
 
 

2 Responses to “Disabling Tab with JavaScript”

  1. Tom
    30. July 2008 at 01:49

    Heya there,

    Just found your post in a search for “javascript override tab key”.

    Your solution didn’t seem to work for me on Firefox 3 (Max OSX)

    I had to use:

    if (evt.keyCode==9) {
    evt.preventDefault();
    evt.stopPropagation();
    }

    Cheers,
    t

  2. Tom
    30. July 2008 at 07:12

    Tom,

    Thanks for the comment - I’ll be sure to point future readers to your comment just in case!

    Tom

Leave a Reply