Submit on enter except when shift is pressed in JavaScript

Josh Sherman
1 min read
Software Development JavaScript TypeScript

Been working on something recently where I wanted to implement a submit handler when a user hits the enter key in an input. That’s not that big of a deal, sniff out the key being pressed, and if it’s the Enter key, go ahead and execute the submit handler.

Since the element in question is an input field, I wanted to allow folks the ability to hold the shift key to enter new line breaks. Best as I can remember, this worked fine with textarea elements, but with a Slate.js editor, not so much.

Not happy with “it is what it is” I decided it was high time that I learned how to handle the detection of modifier keys in conjunction with other keys being pressed.

Turns out, it wasn’t all that hard at all. Simply interrogate the shiftKey on the event to see if the Shift key was being pressed, and continue to check the key value on the event for the Enter key as per usual.

The end result, in the form of my onKeyPress handler:

const onKeyDown = (event: any): void => {
  if (eventkey === 'Enter' && !event.shiftKey) {
    // Enter was hit by itself, do some stuff!

There’s some other variables you can interrogate as well if sniffing other other modifier keys in your thing ;)

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles