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.
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.
Share Improve this question edited May 29, 2016 at 13:02 dbf 3,4631 gold badge26 silver badges34 bronze badges asked May 29, 2016 at 12:51 EhsanEhsan 13k3 gold badges26 silver badges46 bronze badges 2- 4 This question was already asked: see how-to-find-out-what-character-key-is-pressed – wake-0 Commented May 29, 2016 at 12:55
- @KevinWallis So we flag it :) – dbf Commented May 29, 2016 at 13:03
1 Answer
Reset to default 10You 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/javascript/tests/KeyCode.html