*⃣ shortkey
A small library to handle keyboard events in a more declarative way
Install
npm install shortkey
Examples
Both examples use the HTML dialog element. To learn more, check out this demo about the dialog element.
addEventListener()
DOM ; const dialog = document; dialoginnerText = 'Dialog message'; dialog; const button = document; buttoninnerText = 'Open dialog'; button; const fragment = document; fragment; fragment; documentbody;
React and ReactDOM
import React from 'react';import ReactDOM from 'react-dom';import shortkey from 'shortkey'; Component { ; thisdialogRef = React; } { return thisdialogRefcurrent; } thisdialog; handleDialogKeyDown = ; { return <React.Fragment> <button =>Open dialog</button> <dialog = => Dialog message </dialog> </React.Fragment> ; } ReactDOM;
API
Shortkey accepts a plain object. The keys are the event names. The values are the corresponding event handlers. The return value is a function.
The event names are matched against the KeyboardEvent's ctrlKey
, altKey
, shiftKey
, metaKey
and key
attributes (in that order) and prefixed with 'on'
.
;
Check the UI Events KeyboardEvent key Values spec for a list of the key
attribute's possible values.
Browser support
Shortkey supports every browser that supports the KeyboardEvent's key
, ctrlKey
, altKey
, shiftKey
and metaKey
attributes. MDN has a detailed overview of the KeyboardEvent's browser compatibility.
Shim
IE and Edge use non-standard KeyboardEvent.key
identifiers. Depending on the key
you're targetting, you might need a shim.
Note: this isn't necessary if you're using React with ReactDOM
;; const handler = ;