I have a function that fires only when we press the spacebar or the isJumping event is already happening
If we press any other key, nothing happens.
function onJump(e) {
if (e.code !== "Space" || isJumping) return
yVelocity = JUMP_SPEED
isJumping = true
}
The question is, can I add to this function so that, in addition to the space, the mouse click event also fires?
That is, if we press the spacebar or click on the mouse, then the function works
The mouse click event is not key code, so I'm a little confused on how to do it right
If the function is called when you press a key then that is because somewhere in the code you didn't show us you have some code which registers that function (or another function which calls the first) as an event handler that triggers when a key is pressed (e.g. keyup or keypress).
If you want to call it when something is clicked then you also need to register it as an event handler for that kind of event (e.g. click or mousedown).
MDN has a tutorial on event handling.
I assume onJump is attached to a keyboard event handler, presumably on document, something like this:
document.addEventListener("keydown", onJump);
If so, you can also attach it to click:
document.addEventListener("keydown", onJump);
document.addEventListener("click", onJump);
...and then modify the function so it checks which type of event it got and handles it accordingly:
function onJump(e) {
if (isJumping || (e.type === "keydown" && e.code !== "Space")) return;
yVelocity = JUMP_SPEED;
isJumping = true;
}
That will only check e.code if the event is the keydown event, not the click event. (Adjust the event name as necessary).
USE EVENT.TYPE
Use the event.type property when using a single handler for multiple events. In your case, you want the same function to handle keyboard and mouse events. View and run the code snippet below to see how it works.
window.addEventListener("keydown", onJump);
window.addEventListener("mousedown", onJump);
const JUMP_SPEED = 100;
let isJumping = false;
function onJump(e) {
if (e.type === "mousedown") {
// add event handler here
}
else if (e.type === "keydown" && e.code === "Space" && !isJumping) {
yVelocity = JUMP_SPEED
isJumping = true
}
console.log("event: " + e.type + ", isJumping: " + isJumping + ", keycode: " + e.code);
}
<h3>Click the mouse or press spacebar</h3>
<img src="https://cdn.icon-icons.com/icons2/567/PNG/512/packman_icon-icons.com_54382.png" style="height:100px;width:auto"/>