Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript can't capture "SHIFT+TAB" combination

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.

like image 682
Bohemian Avatar asked Apr 18 '11 19:04

Bohemian


2 Answers

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();
});
like image 67
Eli Avatar answered Oct 13 '22 13:10

Eli


I created a function which I wired up to my button's onkeydown event. I used onkeydown, because onkeypress would not capture my tab key press

function ShiftTab(evt) {
        var e = event || evt; // for trans-browser compatibility
        var charCode = e.which || e.keyCode; // for trans-browser compatibility

        if (charCode === 9) {
            if (e.shiftKey) {
                $('#controlName').focus();
                return false;
            } else {
                   return true;
              }
       }

I took this approach to deal with two specific problems:

  1. onkeypress would not capture tab key press
  2. When click shift-tab, shift key press would trigger function, so I had nest the shiftkey modifier check
like image 31
Adriang Avatar answered Oct 13 '22 13:10

Adriang