JavaScript can't capture "SHIFT+TAB" combination

Bohemian picture Bohemian · Apr 18, 2011 · Viewed 24.9k times · Source

For whatever reason I can't capture "SHIFT+TAB" combination. I am using the latest jQuery.

Same result if I use other ajax/javascript, etc.

Here is a simple example that should work as I currently understand it...

event.which or event.KeyCode are always "undefined" only shiftKey exists in a scenario involving a "SHIFT+TAB" or backward keyboard traversal, traditionally inherent in windows based apps/web or otherwise...

    function ShiftTab()
    {
      debugger;
      if(event.KeyCode == 9 && event.shiftKey) // neither this line nor the following work
//      if (event.which == 9 && event.shiftKey) // shift + tab, traverse backwards, using keyboard
      {
        return true;
      }
      else
      {
        return false;
      }
    }

this seems to be yet another item related to tab order that no longer works as it traditionally worked in Microsoft.Net WinForm/WebForm based apps.

Answer

Eli picture Eli · Apr 18, 2011

If you are using jQuery, this should be how the code is working. Make sure keyCode is lower case. Also, jQuery normalizes keyCode into which:

$(document).keyup(function (e) {
    if (e.which === 9 && e.shiftKey) {
        ShiftTab();
    }
});

If you're into terse JavaScript:

$(document).keyup(function (e) {
    e.which === 9 && e.shiftKey && ShiftTab();
});

jQuery 1.7+ on syntax:

$(document).on('keyup', function (e) {
    e.which === 9 && e.shiftKey && ShiftTab();
});