Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how detect CTRL+q in javascript

Tags:

javascript

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.

like image 755
Ehsan Avatar asked Apr 22 '26 07:04

Ehsan


1 Answers

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

like image 119
starbeamrainbowlabs Avatar answered Apr 23 '26 19:04

starbeamrainbowlabs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!