Search code examples
javascripteventsaddeventlistenerkeycode

Keydown and keyup eventlisteners are working properly


I have a code to where I want to detect when someone is pressing a key, then when they release it, the code deletes the code saying they were pressing the key. I tried to piece together some code using information I found online. Here's what I have so far:

 var down = {};
    document.addEventListener("keydown", function(evt) {
        down[evt.keyCode] = true;
        console.log(down)
    });
    document.addEventListener("keyup", function(evt) {
        delete down[evt.keyCode];
    });
var p = 0
if (down(65) == 65 && p - 1 >= 0) {
        p -= 1;
    }
    if (down(65) == 68 && p + 1 <= 9) { 
        p += 1;
    }

The console keeps saying that down is not a function. How am I to read what keycode they're pressing, but also then delete that instance of keycode after they lift the key.


Solution

  • You're not accessing the value of your down correctly. With objects, bracket or dot notation is the way to go:

    var down = {};
    
    document.addEventListener("keydown", function(evt) {
      down[evt.keyCode] = true;
      console.log(down)
    });
    
    document.addEventListener("keyup", function(evt) {
      delete down[evt.keyCode];
    });
    
    var p = 0;
    
    if (down[65] === 65 && p - 1 >= 0) {
      p -= 1;
    }
    if (down[65] == 68 && p + 1 <= 9) {
      p += 1;
    }