3

How detect ctrl+q with javascript, this is my code

<body>
    <p id="x"></p>
    <script>
       window.onkeydown = function() {detect(event);}
       window.onkeypress = function() {res(event);}
       var act = false;
       function detect(event) {
           if(event.ctrlKey) {
              act = true;
           }
           else
               act = false;
       }
        function res(event) {
            if(act) {
                document.getElementById("x").innerHTML = "ctrl " + String.fromCharCode(event.which);
            }
            else
                document.getElementById("x").innerHTML = String.fromCharCode(event.which);
        }
    </script>
</body>

I want do it with javascript only.

dbf
  • 3,278
  • 1
  • 24
  • 34
Ehsan
  • 12,655
  • 3
  • 25
  • 44
  • 4
    This question was already asked: see [how-to-find-out-what-character-key-is-pressed](http://stackoverflow.com/questions/1846599/how-to-find-out-what-character-key-is-pressed) – wake-0 May 29 '16 at 12:55
  • @KevinWallis So we flag it :) – dbf May 29 '16 at 13:03

1 Answers1

10

You can detect it using the following function:

document.addEventListener("keydown", function (event) {
  event.stopPropagation();
  event.preventDefault();

  if(event.ctrlKey && event.keyCode == 81)
  {
    console.log("CTRL + Q was pressed!");
  }
  else
  {
    console.log("Something else was pressed.");
  }
});

The stopPropagation() and preventDefault() calls prevent the browser's default behaviour from occurring.

If you want to detect other keys, this page is rather useful: http://asquare.net/javascript/tests/KeyCode.html

starbeamrainbowlabs
  • 5,692
  • 8
  • 42
  • 73
  • how this code detect q?why press ctrl+b , not working console.log("CTRL + Q was pressed!");? – Ehsan May 29 '16 at 15:00
  • @ehsan `keyCode == 81` refers to the Q key. The B key is something other than 81. –  Sep 21 '16 at 23:34
  • @ehsan Yes. The keyCode `81` is the `Q` key. I have have mentioned in my answer, the provided link is useful in determining the `keyCodes` of other keys. – starbeamrainbowlabs Sep 22 '16 at 09:35