Reputation: 594
I'm trying to fire my masterFunction only if certain keys are pressed. However it's being called regardless of what button is clicked. Even though the console log shows a different key.
Can anyone advise?
//Update display on keydown event
addEventListener('keydown', (e) => {
pressedKey = event.key;
console.log(pressedKey);
keyDownOperatorMapping(e);
});
let keyDownOperatorMapping = (e) => {
if (pressedKey === "+" || "-" || "*" || "Enter" || "Backspace" || "." || "/") {
masterFunction(e);
}
};
Example: https://jsfiddle.net/rykawgs9/
Upvotes: 0
Views: 64
Reputation: 468
You have to put the variable that you are comparing to. Which is in your case, the pressedKey
:
if (pressedKey === "+" || pressedKey === "-" || pressedKey === "*" || pressedKey === "Enter" || pressedKey === "Backspace" || pressedKey === "." || pressedKey === "/")
...
Upvotes: 1
Reputation: 63524
You can reduce the code a little by adding the searchable keys to an array, and then check that the array includes
the key that was entered.
const allowed = ['+', '-', '*', 'Enter', 'Backspace', ',', '/'];
document.addEventListener('keydown', (e) => {
const { key } = e;
if (allowed.includes(key)) {
// masterFunction(e)
console.log(key);
}
});
Additional documentation
Upvotes: 1
Reputation: 445
It is because your current condition is
Hey is pressedKey equal is "+"
or is "-" is true
or //goes on
As string with length more than one is always one it always return true your condition is always true
So one way archive these
addEventListener('keydown', (e) => {
pressedKey = event.key;
console.log(pressedKey);
keyDownOperatorMapping(e);
});
let keyDownOperatorMapping = (e) => {
const keys = ["+", "-", "*", "Enter", "Backspace", ".", "/"]
if (keys.includes(pressedKey)) {
console.log("Found");
}
};
Upvotes: 2