0

I'm making an application that needs to detect whether or not the CTRL key was pressed.

My code is as follows:

    document.addEventListener('keydown', function(event) {
    if (event.keyCode != 13 || event.keyCode != 38 || event.keyCode != 40 || event.keyCode != 17)
        {
            // execute this
        }

(The CTRL key is the last keycode in that if statement.)

After searching the internet it says to use 17 as the keycode, but it is still EXECUTING "// Execute this" if i press CTRL. It's not supposed to execute it.

All other keys work properly in the if statement, and I'm using Chrome 31 stable/official.

I am also using 'keydown' and not 'keypress' as you can see.

Thanks in advance for help!

vahid abdi
  • 9,636
  • 4
  • 29
  • 35
novs12
  • 657
  • 2
  • 7
  • 15

2 Answers2

4

This condition

event.keyCode != 13 || event.keyCode != 38 || event.keyCode != 40 || event.keyCode != 17

will always be true. This can be proven with two cases.

  • If event.keyCode is 13, then event.keyCode != 38 will cause the expression to return true because 13 != 38.

  • If event.keyCode is not 13, then the condition event.keyCode != 13 will cause the expression to return true.

I believe that you are wanting to use the && operator instead of the || operator.

Also, instead of checking event.keyCode !== 17, I think it is more readable to use !event.ctrlKey because it tells the reader of the code that you are checking about the ctrl key, whereas you have to look up 17 in a keycode table in order to find out what it means.

(As an aside, the !== and === operators are preferred in the Javascript community over the != and == operators.)

Community
  • 1
  • 1
Peter Olson
  • 139,199
  • 49
  • 202
  • 242
2

1 Change the or operator to an and operator (&&)

2 Fix your code errors, missing a semicolon and close parentheses

Your final code should look like this:

document.addEventListener('keydown', function (event) {
    if (event.keyCode != 13 && event.keyCode != 38 && event.keyCode != 40 && event.keyCode != 17) {
        alert(event.keyCode);
    }
});

DEMO

Cilan
  • 13,101
  • 3
  • 34
  • 51
  • Thank you very much I did mean to use &&! And I also accidentally cut off my code in here but I did finish the brackets in my code! – novs12 Jan 06 '14 at 02:55