Most Elm keyboard-related packages (such as elm-lang/keyboard, and
others which build on it) only decode the KeyCode from Javascript's
keyboard event (possiby building up some additional state from the
sequence of keycodes).
This ignores some potentially useful information reported in Javascript's keyboard event:
* the state of modifier keys (such as the shift key)
* whether the event is a "repeated" keyboard event (due to a key being held down)
This package provides decoders for that additional information, and examples
of using those decoders when listening for keyboard events on HTML elements,
or the window object itself (as elm-lang/keyboard does).
To listen for keyboard events on HTML elements, you can do something like this:
div
[ on "keydown" <|
Json.Decode.map HandleKeyboardEvent decodeKeyboardEvent
, tabindex 0
, id "id-for-auto-focus"
, style [ ( "outline", "none" ) ]
]
[]See the examples directory in the source code for complete examples.
* Listen for events on an outermost div
* Listen for events on multiple divs
* Listen for events on the window object
Note that an HTML element must be focused in order to receive keyboard events
(unlike in elm-lang/keyboard, since it attaches a listener to the
Javascript window object). This is either an advantage or a disadvantage,
depending on your circumstances. If you want to handle keyboard events
differently depending on what is focused, it is an advantage. Otherwise, you
can work around the need to focus, in this way:
* provide the element with a tabindex attribute (as demonstrated above),
so that it is focusable
* possibly give it a style of outline: none; to avoid the default outline
that would be drawn when the element is focused
* possibly use elm-lang/dom to automatically focus the element when you initialize the page
Alternatively, the examples directory also
contains an example
of subscribing to keyboard events on the window object, as
elm-lang/keyboard does, but supplying your own decoder instead
of just getting the KeyCode. In that case, you can avoid the need to focus on
any particular HTML element.
For the detailed API, see the Elm package site, or the links to the right, if you're already there.
Try elm-package install Gizra/elm-keyboard-event
Try something like:
git clone https://github.com/Gizra/elm-keyboard-event
cd elm-keyboard-event
npm install
npm testYou can then find the compiled examples in the build folder.