Detecting modifier keys being pressed with JavaScript

Been hot on a new [old] project recently and I’ve not only been coding my ass
off, but delving into some territory that I haven’t delved into as of late.

The latest is in terms of determining if a modifier key has been pressed in
conjunction with another key press. So like, Shift being help while a letter
or other key has been tapped.

Turns out, you can detect these modifier quite easily, and there are *Key
values on the event object for all of the major modifier keys like control,
alternate and such.

When interrogating an event object, you can simply look for the following
parameters:

  • event.altKey – For when the alternate (alt) key is being held.
  • event.ctrlKey – For when the control key is being held.
  • event.shiftKey – For when the shift key is being pressed (allows you to
    differentiate between upper and lower cased letters being pressed.
  • event.metaKey – For when the meta (super) key is being held.

Checking the aforementioned values in addition to event.key makes it easy to
determine if the user is pressing Ctrl+F and the like.

Josh Sherman - The Man, The Myth, The Avatar

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.


If you found this article helpful, please consider buying me a coffee.