JavaScript set variable to certain value if key is down

Viewed 61

I'm wondering how I can create something using JavaScript where a variable called x is set to -1 as a default. If the user is pressing any key on their keyboard, the variable will be set to -2. Once they let go of the key and no key is being pressed, the variable will revert back to -1. How can this be done? I've already declared the variable using JavaScript:

let x = -1;

I'm not sure what to do next however. How can this be done?

1 Answers

Use window events:

window.onkeydown = () => {x = -2};

window.onkeyup = () => {x = -1}

Related