0

I'm trying to trigger an event if any key is pressed except the arrows keys or the enter key on a text input field.

myinput.addEventListener('keydown', (e) => {
    if (e.keyCode !== 13 ||
        e.keyCode !== 37 ||
        e.keyCode !== 38 ||
        e.keyCode !== 39 ||
        e.keyCode !== 40 ) {
          console.log('foo');
    }
});

In the above example, my if is ignored and 'foo' appears for every key.

Any idea what I am doing wrong?

user1444027
  • 4,983
  • 7
  • 29
  • 39
  • 6
    You want to use `&&`, not `||`. The condition you have there will always be true. – John Montgomery May 11 '20 at 22:18
  • Maybe you would need to use multiple else if and put your keycodes there – Loki May 11 '20 at 22:19
  • 1
    Or `![13, 37,38,39,40].includes(e.keyCode)` – Mosh Feu May 11 '20 at 22:21
  • 1
    @MoshFeu that's really neat thank you! – user1444027 May 11 '20 at 22:23
  • This is a very common mistake I see all the time, it's almost as if conditional logic is counter-intuitive to us humans. I guess it must have something to do with how we humans use language. As in, in speech we usually don't express a condition like this as _"it can't be this **and** it can't be that"_. Instead we take a shorthand and say _"it can't be this **or** that"_. – Lennholm May 11 '20 at 22:32
  • @Lennholm But the latter is valid too as long as you interpret it as *"it can't be (this or that)"*. – John Montgomery May 11 '20 at 22:41
  • @JohnMontgomery But such a statement can't be expressed with operators in Javascript. That's why, I think, people make this mistake. – Lennholm May 11 '20 at 22:51
  • @Lennholm Sure it can, `!a && !b` is equivalent to `!(a || b)`. – John Montgomery May 11 '20 at 22:53
  • @Lennholm Actually it's a misunderstanding that "it can't be this or that" means the same thing as "it can't be this or can't be that". When in fact "it can't be (this or that)" means "(it can't be this) and (it also can't be that)". Even in spoken English this logic applies: "son, don't run around the swimming pool **and** don't squirt that water gun at people!" - nobody who speaks English will use **or** in this case because using **or** implies that the kid have a choice of either squirting his water gun at people or run around the swimming pool – slebetman May 11 '20 at 23:51

0 Answers0