Home > Back-end >  combination of buttons in event OnKeydown
combination of buttons in event OnKeydown

Time:11-12

I need to set up combination of buttons in input form of my react app.

  1. "CTRL "ArrowUp"
  2. "ArrowUp"

My code is something like this.

//Form

<input onKeyDown={keyHandler}/>

//handler

const keyhandler = (e) => {

if(e.key === "ArrowUp") {//do something}

if(e.key === 'ArrowUp' && e.getModifierState("Control")) {//do another thing}

The problem is when event fired with combination, first 'if' also true. How separate "ArrowUp" and "ArrowUp" with ctrl button?

I also try like this (but it didn't help):


if(e.key === 'ArrowUp' && event.ctrlKey){ //do another thing}

CodePudding user response:

Just following your logic,

  if (Control is pressed) {
    if (ArrowUp is pressed) {
        // both are pressed
    }
  } else {
    if (ArrowUp is pressed) {
        // only arrow up is pressed
    }
  }

CodePudding user response:

I solved my problem by using this one.

if(!e.getModifierState('Control')){
 if(e.key == 'ArrowUp'){ 
  //single button action
  }
}
if(e.key == "ArrowUp" && e.getModifierState("Control")){
 //combo buttons action
}
  • Related