ehsan ehsan - 6 months ago 21
Javascript Question

how detect CTRL+q in 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.

Answer

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