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>
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>
Share
Improve this question
edited Nov 5, 2020 at 14:11
Brian Tompsett - 汤莱恩
5,89372 gold badges61 silver badges133 bronze badges
asked Aug 25, 2015 at 14:56
bool3maxbool3max
2,8757 gold badges32 silver badges64 bronze badges
6
- Can you show the HTML code of the input field, too, please? – danielaKay Commented Aug 25, 2015 at 15:04
- Added it now. @danielaKay – bool3max Commented Aug 25, 2015 at 15:12
- I just tried your jsfiddle both in Firefox and Chrome, none of them work. ?? – bool3max Commented Aug 25, 2015 at 15:19
-
Yeah, sorry. I only tested letters, and that works with
e.which
:-/ The ctrl key still doesn't work. My bad. – danielaKay Commented Aug 25, 2015 at 15:22 - Yeah, letters do work, I said that in my post :P . Also, it's not working with other special keys, not just ctrl. – bool3max Commented Aug 25, 2015 at 15:24
3 Answers
Reset to default 5For some reason, special keys do not work with the keypress
event, but they do with the keydown
event.
Try this instead: (e.which == 17)
Check for e.ctrlKey
.
See the MDN documentation at https://developer.mozilla/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/