105

I am working on key mapping. The problem is that when I press the TAB button down it navigates to the next input field.

TAB has key of 9 and
DOWN has key of 40

But, what is the JavaScript key code to go to the previous input field (SHIFT + TAB)?

What I want is to go to next link; what is keycode or code for the previous link?

Please help. Thanks.

rfornal
  • 5,072
  • 5
  • 30
  • 42
rajesh
  • 1,413
  • 2
  • 17
  • 23

5 Answers5

205

There's no "keycode", it's a separate property on the event object, like this:

if(event.shiftKey && event.keyCode == 9) { 
  //shift was down when tab was pressed
}
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • what i want is if i click on up key it should go to previously selected tab so please provide some suggestion.. tahnks – rajesh Jun 15 '10 at 09:57
  • @rajesh - Can you clarify a bit? Your question asks for they keycode for shift+tab, but you want to detect the up key? – Nick Craver Jun 15 '10 at 10:02
  • ya what i want if i click p button it must move to upper field which has a function like shift+tab. Hence the same i want – rajesh Jun 15 '10 at 10:14
  • @rajesh - Are you using any JavaScript libraries or no? If you're not, this is probably what you're after: http://stackoverflow.com/questions/702585/simulating-a-tab-keypress-using-javascript – Nick Craver Jun 15 '10 at 10:33
  • 3
    There IS a keycode for the keydown event - Shift+Tab keyCode=16 – Peter Davis Nov 21 '12 at 02:21
  • 12
    Peter, the keyCode 16 is for the Shift key. – dkubb Jan 23 '13 at 08:06
29

e.keyCode has been deprecated for sometime. Use "e.key" KeyboardEvent.key instead.

Usage:

e.shiftKey && e.key === 'Tab'

Example:

function clicked(e) {
    if (e.shiftKey && e.key === 'Tab') {
        // Do whatever, like e.target.previousElementSibling.focus();
    }
}
Modular
  • 6,440
  • 2
  • 35
  • 38
  • 1
    best answer. actual working usecase. Especially for angular. if you're using keycodes in these days you're doing it wrong. – tatsu Jul 16 '18 at 16:02
  • 1
    People keep saying that keycode is depreciated, but as of 2021 there's still not enough support for event.key - https://caniuse.com/keyboardevent-key – John Ohara May 25 '21 at 11:04
7

you can use the event.shiftKey property for that: http://www.java2s.com/Code/JavaScript/Event/Shiftkeypressed.htm

knittl
  • 246,190
  • 53
  • 318
  • 364
3

This way it worked for me
By checking first if one of key is pressed(tab/shift ) and then check other inside it:

if (e.code === "Tab") {
  if (e.shiftKey) {//shift+tab pressed
      //Code
  } else {//only tab pressed
      //Code
  }
}
Rana
  • 2,500
  • 2
  • 7
  • 28
  • Don't know why keeping both conditions in one won't work for me. As good answers are already provided but thought to add this. – Rana Dec 30 '21 at 14:27
0

in my GWT case

if(event.isShiftKeyDown() && event.getNativeKeyCode() == KeyCodes.KEY_TAB){
    //Do Something
}
touchchandra
  • 1,506
  • 5
  • 21
  • 37