Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Object-Oriented JavaScript: Challenge Making the Game Interactive handleKeydown() Solution

Console is throwing error and my console log isn't working

The console says "Uncaught TypeError: Cannot read property 'key' of undefined at Game.handleKeyDown (Game.js:34) at HTMLDocument.<anonymous> (app.js:10)" however many times you press a key, I'm not sure why. Here is my code for the handleKeyDown method:

handleKeyDown (e) {
    if (this.ready) {
        if (e.key === "ArrowLeft") {
            console.log("hello"); //checking if it works, which it doesn't for some reason
        } else if (e.key === "ArrowRight") {

        } else if (e.key === "ArrowDown") {

        }
    }
}

and the keydown event listener in app.js in case you need it:

document.addEventListener('keydown', (event) => {
    game.handleKeyDown();
})

1 Answer

Cameron Childres
Cameron Childres
11,817 Points

Hi babyoscar,

In your event listener you have event as a parameter but you aren't passing it to game.handleKeyDown(). When the handleKeyDown() function runs it doesn't have any arguments to work with. Try this out:

document.addEventListener('keydown', (event) => {
    game.handleKeyDown(event);
});

Thanks! It worked.