Check for modifier keys when using jQuery's .keyPress()

PostJul 6th, 2010 | Comments (4)
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 mofifier 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

Comments

florinNov 24, 2010
Thanks. I needed that.
levuDec 22, 2010
thx, why isn't this in official jQuery documentation? :)
GuillaumeFeb 23, 2011
I think this only works in Firefox, but not in Chrome nor IE...
Jamie TibbettsFeb 23, 2011
You're right, Guillaume. It does only work in Safari and Firefox. In IE, alt-enter resizes the window. :(

Post a comment

Name
URL
Email
Comment