5

I want to use shortcut to handle a task in Javascript (not JQuery or any Javascript libraries). For example, I want to use Ctrl+Q to write an alert. My issue is only to use Ctrl+Q, combination of other keys such as Ctrl+Q+other key will not handle the alert. How can I do?

document.addEventListener('keydown', function(event){
  if(event.ctrlKey && event.keyCode == 81) console.log('alert');
});

I only want Ctrl+Q work, not for Ctrl+Shift+Q, Ctrl+Alt+Q, Ctrl+Q+(some key else)

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Freelancer
  • 837
  • 6
  • 21
  • Maybe duplicate of [How to detect if multiple keys are pressed at once using JavaScript?](https://stackoverflow.com/questions/5203407/how-to-detect-if-multiple-keys-are-pressed-at-once-using-javascript) – nagataaaas Jul 01 '19 at 03:48

3 Answers3

4

Just ensure none of the other three modifiers are pressed:

document.addEventListener('keydown', function(event) {
  if (event.ctrlKey && event.keyCode == 81 && !(event.shiftKey || event.altKey || event.metaKey)) console.log("alert");
});
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

The code below should solve your problem(Updated Code):

document.addEventListener("keydown", function (event) {
var map = [];
  onkeyup = function(e){
    map.push(e.key);
    console.log(map);
    if(map.length == 2){
      console.log("CTRL + Q was pressed",map.indexOf("q") > -1 && map.indexOf("Control") > -1)
    }

    onkeydown = function(e){
      // console.log(map);
    }
  }


});

If any other button is pressed along with ctrl (For instance: ctrl+shift+Q or ctrl+alt+q), it returns false!! Let me know if that solves your problem. Cheers!!

Suraj Mohata
  • 106
  • 1
  • 5
-1

You'll need to keep track of what keys are pressed with keydown and which keys are released with keyup, then, when a new key is pressed, you would check for only Ctrl and Q currently being down.

Something like this should work:

var keysPressed = [];

function onPressOrRelease(event) {
  if (event.type === "keydown") {
    if (!keysPressed.includes(event.keyCode))
      keysPressed.push(event.keyCode)
  } else if (event.type === "keyup")
    keysPressed.splice(keysPressed.indexOf(event.keyCode), 1);

  let ctrlQPressed = keysPressed.includes(81) && keysPressed.includes(17) && !keysPressed.some(a => a !== 81 && a !== 17)
  if (ctrlQPressed)
    console.log("pressed");
}

document.addEventListener("keydown", onPressOrRelease);
document.addEventListener("keyup", onPressOrRelease);

You'll want to make sure keys don't get added multiple times and may want to clear the array on focus loss (since using control it may lose focus when releasing)

Seth
  • 972
  • 1
  • 7
  • 18
  • I'm not sure why someone thought this was worthy of a down vote but I'm pretty sure this is the only way to tell for instance that someone isn't holding down 'Q+E+Ctrl' or any other combo of Ctrl+Q+(some key else) as requested in the question – Seth Jul 01 '19 at 04:13