Skip to content Skip to sidebar Skip to footer

Javascript Eventlistener Not Working

I want to make a startscreen with the function to start the game when the user presses SPACE but my code doesn't work. var level1 = false var keys = []; window.addEventListener('k

Solution 1:

but when i press SPACE the variable level1 is still on false

Yes. Why would it be anything else? Nothing in your event handlers is updating it.

If you want to update it when an event occurs, update it in the event handler.

Perhaps have a function that updates the state of any variables you want tracking key state and call it from both event handlers:

var level1 = falsevar keys = [];

window.addEventListener("keydown", function(e) {
    keys[e.keyCode] = true;
    checkKeyState();
}, false)

window.addEventListener("keyup", function(e) {
    delete keys[e.keyCode];
    checkKeyState();
}, false)

context.font = "bold 35px Arial";
context.fillText("Press Space to Start", 290, 300);

functioncheckKeyState() {
    if (keys[32]) {
        level1 = true;
    } else {
        level1 = false;
    }
}

Note that checkKeyState can also be written:

function checkKeyState() {
    level1 = !!keys[32];
}

...but I didn't want to throw that at you in the first code block.

Solution 2:

In example code you provided, the if statement that checks keys[32] runs before any event is fired. So you need to move the body of the if statement into the keydown event function:

window.addEventListener("keydown", function(e){
    keys[e.keyCode] = true;
    level1 = true;
}, false);

Post a Comment for "Javascript Eventlistener Not Working"