Bestlogo56
Bestlogo56

Reputation: 75

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.

Upvotes: 0

Views: 58

Answers (3)

Joulss
Joulss

Reputation: 1189

It's down['65'], not down(65).

You should also test if down['65'] exists before comparison :

if (down['65'] && down['65'] == 65 && p - 1 >= 0) {
    p -= 1;
}
if (down['65'] && down['65'] == 68 && p + 1 <= 9) { 
    p += 1;
}

Upvotes: 1

karim
karim

Reputation: 11

Just change down(65) to down[65] to get it's value.

down(65) calling down as function

down[65] accessing value of index 65 of a array called down'

Upvotes: 1

Carl Edwards
Carl Edwards

Reputation: 14464

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;
}

Upvotes: 1

Related Questions