Reputation: 37
I have some javascript code where a varible is set to 1 when a key is down but when a key isn't being pressed, the variable is set to 0. How can I modify the code so instead of when any key is being pressed the variable is set to 1, only when the key c is pressed the variale will be set to 1. How can this be done? Current code:
let x = 0;
window.onkeydown = () => {
let x = 1;
};
window.onkeyup = () => {
let x = 0;
}
Upvotes: 0
Views: 268
Reputation: 603
Use the keyup or keydown events from jQuery, tested example below.
In those function you can pass in event
and from there you can use event.keyCode
for the specific key that has been pressed.
If you want to add keys but don't know the keyCode you can just simply add console.log(event.keyCode);
inside the keydown block.
I added the example below to JSFiddle, make sure to click on the Right Bottom of the screen before pressing the key. You can also open the log inside JSFiddle to see the keyCode. Goodluck! https://jsfiddle.net/h6exry0t/
$(document).ready(function(){
let x = 0
$(document).on('keydown', function (event) {
if(event.keyCode === 67){
x = 1;
}
});
$(document).on('keyup', function (event) {
if(event.keyCode === 67){
x = 0;
}
});
});
Upvotes: 1