Check for modifier keys when using jQuery's .keyPress()
I was developing a simple chat log for a website, and I wanted the user to be able to submit a message when they hit the "enter" key but not if the "alt/option" key is being pressed. If the "alt/option" key is being pressed while the user hits the "enter" key, I want a carriage return to be entered in the chat field instead.
The jQuery .keyPress() doc page is a bit light on details, so here's how you can check for modifier keys with the .keyPress() event handler:
$('textarea#chat_message').keypress(function(e) {
if (e.which == 13) { // enter key was pressed
if (e.altKey) { // alt/option key is down
// don't submit
}
else {
// submit
}
}
});
The modifier keys you can test for are:
altKey - alt/option key
ctrlKey - control key
shiftKey - shift key
metaKey - control key on PCs, control and/or command key on Macs
Thanks. I needed that.
thx, why isn't this in official jQuery documentation? :)
I think this only works in Firefox, but not in Chrome nor IE...
You're right, Guillaume. It does only work in Safari and Firefox.
In IE, alt-enter resizes the window. :(
@levu Because "eventhandler" is a javascript object, so altkey should be in Javascript docs
Exactly what I was looking for when figuring out how to not have Firefox fire on "Ctrl-C" when I am only expecting it to fire on "c".
Leave a Comment