JavaScript set variable to certain value if key is down

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 answer

  • answered 2021-07-27 18:06 sid c

    Use window events:

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

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

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum