Test Your Skills: Events, Events 2: Keyboard Events

For some reason I am having a hard time wrapping my head around JS, I feel like I can’t really understand it at a very fundamental level, so thank you for your patience!

So, re the “Test Your Skills” exercise for “Events” where “you need to build an event handler that moves the circle around the provided canvas when the WASD keys are pressed on the keyboard”, it seems to me that you need an event listener for when a key is pressed (“keydown” ), then you need to know what key it was (it needs to be up/down/left/right), which would be “keyboardEvent.key”, then, you need to change the x,y variables based on that key to move the circle, right?

So, the code would look something like this, for the instance of moving the circle up:

window.addEventListener(“keydown”, function (event) {
if (event.key === “ArrowUp”) { y–; }
}

I’ve added an event listener for the window for when a key is pressed, which is equal to a function that sees if the key was the arrow up, in which case the y value for the circle location is reduced.

Now I’m quite hazy about this, especially the event parameter, but in any case, where do I go from here? Do I need to refer this back to the “canvas” or “ctx” (circle) variables? Am I mistaken in how to change the x,y variables, is it not so easy as just “y–”? Any hints are appreciated, thanks!

2 Likes

Hi, I eventually solved it; I was on the right track, but what I was missing was that the “if” statement has to call back to the “drawCircle” function, so the code looks like this (*just the case of moving the circle up, but the premise is the same for other directions):

document.onkeydown = function(event) {
const keyName = event.key;
if (keyName === “w”) {drawCircle(x, y–, size);}
}

So, there is a “key down” event listener, which calls a function with an event parameter, and if that parameter is the key “w”, then the drawCircle function is called with a reduced y value, moving the circle up. Repeat for other directions. done! even though there are no comments, thanks for reading! happy coding

1 Like

@ahpto nice work! This is a tricky one to figure out, so you did really well.

Our version uses a switch statement, but using if/else if is equally valid.

1 Like

@chrisdavidmills Thanks for sharing the MDN version. Very usefull. I went with a basic solution which called the drawcircle once going through the if statements. I did use the MDN Keyboard Events to understand things better. BTW is there a way to show markdown code on discourse? Still getting my bearing on discourse.
My code is as follows

document.addEventListener(‘keydown’, (event)=> {
let keyName = event.key;
console.log(keyName);
if(keyName === ‘w’) {
y -= 1;
} else if (keyName === ‘s’){
y += 1;
} else if (keyName === ‘a’){
x -= 1;
} else if (keyName === ‘d’){
x += 1;
}
drawCircle(x, y, size);
});