-2

So I have been using a nested if-else & event.which for handling all the keyboard navigation, but I want to change to switch-case & event.key.

I am facing trouble in handling shift+tab event.
I've tried:

switch(event.key){
  case "Shift":
    console.log("entering shift");
    if(event.key === "Tab"){//do something}
    console.log("exiting shift");
    break;
  case "Tab":
    //handling only tab events
    break;
}

But this does not seem to work. The control enters shift block & leaves shift block, without entering if(event.key === "Tab") part. Hence, I'm unable to handle SHIFT + TAB.

Also tried case "Shift" && "Tab":{}, but this is hindering with Tab-only block.

Is there a way to handle SHIFT + TAB inside switch-case.

Prakhar
  • 53
  • 8
  • 2
    `event.key` holds a single key event. You would need a mechanism to store previous keydown events. idk if jquery has something precisely for this, with plain js you could follow: https://www.gavsblog.com/blog/detect-single-and-multiple-keypress-events-javascript or https://stackoverflow.com/questions/5203407/how-to-detect-if-multiple-keys-are-pressed-at-once-using-javascript for example – malarres Sep 03 '21 at 06:25
  • 1
    This may help - https://stackoverflow.com/a/68428563/5518817 – T.Shah Sep 03 '21 at 06:29
  • No, the shift state and the value of key are two separate pieces of information. You would need at minimum a case statement *and* an if statement. however, skipping the switch would simplify the whole thing down to a single conditional. – Kevin B Sep 03 '21 at 20:50

1 Answers1

1
switch(event.key){
  case "Shift":
    console.log("entering shift");
//you enter this case because event.key === "Shift"
//so event.key === "Tab" will always be false
    if(event.key === "Tab"){//do something}
    console.log("exiting shift");
    break;

I don't think you really need to use switch here as some simple ifs will do fine:

let shift = false;
document.addEventListener('keydown', event => {
  if (event.key === 'Shift') {
     shift = true;
  }
});
document.addEventListener('keyup', event => {
   if (event.key === 'Shift') {
      shift = false;
   }

   if (event.key === 'Tab' && shift) {
      //do stuff
   }
  }
});
  • the event object has a flag for whether or not the shift key is pressed, can't that be used instead of keeping your own shift key flag? – Kevin B Sep 03 '21 at 20:54
  • The fact that I should handle keyup event for shift separately, helped me solve the issue :) thanks @CaryHarper – Prakhar Sep 05 '21 at 11:42