novs12
novs12

Reputation: 667

JavaScript - CTRL KeyCode of 17 does not work?

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!

Upvotes: 0

Views: 869

Answers (2)

Peter Olson
Peter Olson

Reputation: 142931

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.)

Upvotes: 4

Abraham Hamidi
Abraham Hamidi

Reputation: 13809

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

Upvotes: 2

Related Questions