Stimulus - KeyboardEvent 101

Use Stimulus' built in KeyboardEvent functionality to handle basic hotkeys.

View Solution on Patreon
Stimulus - KeyboardEvent 101

Premise

If you wanted to add convenient keyboard shortcuts to your application, you used to have to fall back to third party libraries like hotkeys.js. Since a while ago, you can now leverage Stimulus’ native KeyboardEvent filter functionality to achieve the same result - at least for more basic use cases.

Challenge

Implement a way to dynamically add/remove input fields, as well as alter their types, using hotkeys:

Here are a few suggestions:

  • alt+up/down to add or remove inputs (ensure that you clone the enclosing div!)
  • ctrl+0/9 to cycle through the valid types. My suggestion would be to use value change callbacks for this again.

Make sure to disallow the removal of non-empty inputs, and focus on the newly added one in case of insertion, or the previous element in case of removal.

Managing Form Fields Dynamically

Caveats

  • make sure to leave at least one input!
  • you cannot override any system shortcuts (and it’s also an accessibility antipattern)

Teaser

In Stimulus, how could you respond to a new input element being added, or one being removed?

More from

Faceted Search with Stimulus and Turbo Frames
10 December 2024

Harness the power of Stimulus and Turbo Frames to drive a simple but powerful faceted search solution

Stimulus - Video Progress Tracker with LocalStorage
29 October 2024

Store ephemeral user state like video playback progress in localStorage

Stimulus - Image Upload Previews with `URL.createObjectURL`
17 September 2024

Create client-side previews of files using URL.createObjectURL

Cookies
essential