Pure JavaScript to detect only Ctrl+Q shortcuts

Viewed 441

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)

3 Answers

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

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!!

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)

Related