bool3max
bool3max

Reputation: 2865

CTRL keyCode (17) not working in JavaScript?

I have the following code which adds an eventListener to a HTML textarea. It's supposed to console log the keycode which was pressed, and, if the keyCode is == to 17 (CTRL), console log "You pressed CTRL.". For some reason, when I press CTRL in the textarea, it's not console logging the keyCode which was pressed, nor "You pressed CTRL." If I press "A" for example, console log return "97" which is correct. It also works with all other letters.

Here's the code:

document.getElementById("msgBox").addEventListener("keypress",function(e){
    console.log(e.keyCode);
    if(e.keyCode == 17){
        console.log("You pressed CTRL.");
    }
});

What am I doing wrong?

UPDATE : It's also not working with other special keys like "shift, Fx, alt, home etc.

HTML for the textarea :

<textarea id="msgBox" placeholder="Enter your message" autofocus></textarea>

Upvotes: 0

Views: 3967

Answers (3)

bool3max
bool3max

Reputation: 2865

For some reason, special keys do not work with the keypress event, but they do with the keydown event.

Upvotes: 5

lifeisfoo
lifeisfoo

Reputation: 16294

Check for e.ctrlKey.

See the MDN documentation at https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/ctrlKey

If you want an easy way to manage keypress you could use a dedicated library like https://dmauro.github.io/Keypress/

Upvotes: 0

MHardwick
MHardwick

Reputation: 644

Try this instead: (e.which == 17)

Upvotes: 1

Related Questions