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.
