简体   繁体   中英

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.

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

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM