joshtronic

in Software Development #JavaScript #TypeScript

Submit on enter except when shift is pressed in JavaScript

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 ;)