javascriptjquerydom-eventskeyboard-events

How to handle Shift + Tab inside switch case?


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.


Solution

  • 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
       }
      }
    });