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

Stimulus - Orchestrate Complex UI Changes with Target Callbacks
07 May 2024

Use Stimulus target callbacks to dynamically update parts of your UI

Stimulus - Progressive Image Loading with Blurhash
23 April 2024

Improve Largest Contentful Paint using image blurhashes and Stimulus

Hotwire Combobox with Real Time Data
12 March 2024

Update combobox options using Websockets and Stimulus outlets

Cookies
essential