Top Related Projects
A keyboard input capturing utility in which any key can be a modifier key.
Simple library for handling keyboard shortcuts in Javascript
A simple micro-library for defining and dispatching keyboard shortcuts. It has no dependencies.
A JavaScript library for binding keyboard combos without the pain of key codes and key combo conflicts.
➷ A robust Javascript library for capturing keyboard input. It has no dependencies.
Quick Overview
Tinykeys is a minimal and lightweight JavaScript library for handling keyboard shortcuts in web applications. It provides a simple and intuitive API for defining and managing keyboard combinations, making it easy to add keyboard navigation and shortcuts to your web projects.
Pros
- Lightweight and minimal, with no dependencies
- Easy to use and integrate into existing projects
- Supports complex key combinations and sequences
- Works well with modern JavaScript frameworks and vanilla JS
Cons
- Limited advanced features compared to more comprehensive libraries
- May require additional code for more complex use cases
- Documentation could be more extensive
- Not actively maintained (last update was in 2020)
Code Examples
Basic usage:
import tinykeys from "tinykeys";
tinykeys(window, {
"Shift+D": () => {
console.log("The 'Shift' and 'D' keys were pressed at the same time");
},
"y e e t": () => {
console.log("The keys 'y', 'e', 'e', and 't' were pressed in order");
},
"$mod+KeyZ": () => {
console.log("Either 'Control+Z' or 'Meta+Z' were pressed");
},
});
Using with React:
import React, { useEffect } from "react";
import tinykeys from "tinykeys";
function App() {
useEffect(() => {
const unsubscribe = tinykeys(window, {
"Shift+R": () => {
console.log("Refresh the page");
},
});
return () => {
unsubscribe();
};
}, []);
return <div>My App</div>;
}
Custom key mappings:
import tinykeys from "tinykeys";
const customKeyMap = {
"ArrowUp": "Up",
"ArrowDown": "Down",
"ArrowLeft": "Left",
"ArrowRight": "Right",
};
tinykeys(window, {
"Up Down Left Right": () => {
console.log("Konami Code activated!");
},
}, { keymap: customKeyMap });
Getting Started
-
Install the library:
npm install tinykeys
-
Import and use in your project:
import tinykeys from "tinykeys"; tinykeys(window, { "Control+S": (event) => { event.preventDefault(); console.log("Save action triggered"); }, "Command+Shift+P": () => { console.log("Open command palette"); }, });
-
For more advanced usage and options, refer to the GitHub repository documentation.
Competitor Comparisons
A keyboard input capturing utility in which any key can be a modifier key.
Pros of Keypress
- More comprehensive feature set, including support for key combinations and sequences
- Extensive documentation and examples
- Mature project with a larger user base and community support
Cons of Keypress
- Larger file size and potentially higher performance overhead
- Less actively maintained, with the last update in 2016
- More complex API, which may be overkill for simple use cases
Code Comparison
Keypress:
var listener = new window.keypress.Listener();
listener.simple_combo("shift s", function() {
console.log("You pressed shift and s");
});
tinykeys:
import tinykeys from "tinykeys";
tinykeys(window, {
"Shift+S": () => {
console.log("You pressed shift and s");
},
});
Summary
Keypress offers a more feature-rich solution with extensive documentation, making it suitable for complex keyboard interactions. However, it's less maintained and has a larger footprint. tinykeys, on the other hand, provides a simpler, more lightweight alternative with a focus on modern JavaScript practices and active maintenance. The choice between the two depends on the specific requirements of your project and the level of complexity needed in keyboard event handling.
Simple library for handling keyboard shortcuts in Javascript
Pros of Mousetrap
- More comprehensive feature set, including support for key sequences and special keys
- Larger community and longer development history, potentially leading to better stability
- Supports older browsers and has no dependencies
Cons of Mousetrap
- Larger file size (4.8KB minified) compared to Tinykeys (1KB minified)
- More complex API, which may be overkill for simple use cases
- Less active development in recent years
Code Comparison
Mousetrap:
Mousetrap.bind('ctrl+shift+k', function() {
console.log('Ctrl+Shift+K pressed');
});
Tinykeys:
import tinykeys from "tinykeys";
tinykeys(window, {
"Control+Shift+K": () => console.log("Ctrl+Shift+K pressed"),
});
Both libraries offer similar functionality for basic key binding, but Mousetrap's syntax is slightly more concise. However, Tinykeys uses a more modern import-based approach and provides a cleaner object-based configuration.
A simple micro-library for defining and dispatching keyboard shortcuts. It has no dependencies.
Pros of Keymaster
- More comprehensive feature set, including support for key sequences and multiple shortcuts
- Longer development history and larger community, potentially leading to better stability and support
- Cross-browser compatibility, including older browsers
Cons of Keymaster
- Larger file size (around 4KB minified) compared to Tinykeys' ultra-lightweight approach
- More complex API, which may be overkill for simple use cases
- Less active development in recent years
Code Comparison
Keymaster:
key('⌘+r, ctrl+r', function() {
alert('stopped reload!');
return false;
});
Tinykeys:
import tinykeys from "tinykeys";
tinykeys(window, {
"Control+r": (event) => {
event.preventDefault();
alert('stopped reload!');
}
});
Both libraries allow for easy key binding, but Keymaster's syntax is slightly more concise. However, Tinykeys offers a more modern, modular approach with its import statement and object-based configuration.
A JavaScript library for binding keyboard combos without the pain of key codes and key combo conflicts.
Pros of KeyboardJS
- More comprehensive feature set, including support for key combinations and sequences
- Better cross-browser compatibility, especially for older browsers
- Provides additional utilities like key mapping and locale support
Cons of KeyboardJS
- Larger file size, which may impact page load times
- More complex API, potentially steeper learning curve for beginners
- Less frequently updated, with the last major release in 2019
Code Comparison
KeyboardJS:
KeyboardJS.bind('ctrl + shift + a', function(e) {
console.log('Ctrl+Shift+A pressed');
});
tinykeys:
import tinykeys from "tinykeys";
tinykeys(window, {
"Control+Shift+A": () => console.log("Ctrl+Shift+A pressed"),
});
Both libraries allow for binding key combinations, but KeyboardJS uses a more traditional event-based approach, while tinykeys employs a more modern, object-based syntax. tinykeys is more concise and arguably easier to read, especially when binding multiple shortcuts. However, KeyboardJS offers more flexibility in terms of event handling and additional features like key sequences.
➷ A robust Javascript library for capturing keyboard input. It has no dependencies.
Pros of hotkeys-js
- More comprehensive feature set, including support for various key combinations and modifiers
- Extensive documentation and examples provided in the README
- Supports multiple keyboard layouts and international keyboards
Cons of hotkeys-js
- Larger file size and potentially higher overhead compared to tinykeys
- More complex API, which may be overkill for simple use cases
- Requires more setup and configuration for basic functionality
Code Comparison
tinykeys:
import tinykeys from "tinykeys";
tinykeys(window, {
"Shift+D": () => {
console.log("The 'Shift' and 'd' keys were pressed at the same time");
},
});
hotkeys-js:
import hotkeys from "hotkeys-js";
hotkeys("shift+d", function(event, handler) {
console.log("The 'Shift' and 'd' keys were pressed at the same time");
});
Both libraries offer similar functionality for basic key bindings, but hotkeys-js provides more advanced features and configuration options. tinykeys focuses on simplicity and a smaller footprint, making it ideal for projects with basic hotkey needs. hotkeys-js is better suited for applications requiring complex key combinations and extensive customization.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
tinykeys
A tiny (~650 B) & modern library for keybindings. See Demo
Install
npm install --save tinykeys
Or for a CDN version, you can use it on unpkg.com
Usage
import { tinykeys } from "tinykeys" // Or `window.tinykeys` using the CDN version
tinykeys(window, {
"Shift+D": () => {
alert("The 'Shift' and 'd' keys were pressed at the same time")
},
"y e e t": () => {
alert("The keys 'y', 'e', 'e', and 't' were pressed in order")
},
"$mod+([0-9])": event => {
event.preventDefault()
alert(`Either 'Control+${event.key}' or 'Meta+${event.key}' were pressed`)
},
})
Alternatively, if you want to only create the keybinding handler, and register it as an event listener yourself:
import { createKeybindingsHandler } from "tinykeys"
let handler = createKeybindingsHandler({
"Shift+D": () => {
alert("The 'Shift' and 'd' keys were pressed at the same time")
},
"y e e t": () => {
alert("The keys 'y', 'e', 'e', and 't' were pressed in order")
},
"$mod+KeyD": event => {
event.preventDefault()
alert("Either 'Control+d' or 'Meta+d' were pressed")
},
})
window.addEventListener("keydown", handler)
React Hooks Example
If you're using tinykeys within a component, you should also make use of the
returned unsubscribe()
function.
import { useEffect } from "react"
import { tinykeys } from "tinykeys"
function useKeyboardShortcuts() {
useEffect(() => {
let unsubscribe = tinykeys(window, {
// ...
})
return () => {
unsubscribe()
}
})
}
Commonly used key
's and code
's
Keybindings will be matched against
KeyboardEvent.key
andKeyboardEvent.code
which may have some names you don't expect.
Windows | macOS | key | code |
---|---|---|---|
N/A | Command / â | Meta | MetaLeft / MetaRight |
Alt | Option / ⥠| Alt | AltLeft / AltRight |
Control | Control / ^ | Control | ControlLeft / ControlRight |
Shift | Shift | Shift | ShiftLeft / ShiftRight |
Space | Space | N/A | Space |
Enter | Return | Enter | Enter |
Esc | Esc | Escape | Escape |
1 , 2 , etc | 1 , 2 , etc | 1 , 2 , etc | Digit1 , Digit2 , etc |
a , b , etc | a , b , etc | a , b , etc | KeyA , KeyB , etc |
- | - | - | Minus |
= | = | = | Equal |
+ | + | + | Equal * |
Something missing? Check out the key logger on the demo website
* Some keys will have the same code as others because they appear on the same key on the keyboard. Keep in mind how this is affected by international keyboards which may have different layouts.
Key aliases
In some instances, tinykeys will alias keys depending on the platform to simplify cross-platform keybindings on international keyboards.
AltGraph
(modifier)
On Windows, on many non-US standard keyboard layouts, there is a key named
Alt Gr
or AltGraph
in the browser, in some browsers, pressing Control+Alt
will report AltGraph
as being pressed instead.
Similarly on macOS, the Alt
(Option
) key will sometimes be reported as the
AltGraph
key.
Note: The purpose of the Alt Gr
key is to type "Alternate Graphics" so you
will often want to use the event.code
(KeyS
) for letters instead of
event.key
(S
)
tinykeys(window, {
"Control+Alt+KeyS": event => {
// macOS: `Control+Alt+S` or `Control+AltGraph+S`
// Windows: `Control+Alt+S` or `Control+AltGraph+S` or `AltGraph+S`
},
"$mod+Alt+KeyS": event => {
// macOS: `Meta+Alt+S` or `Meta+AltGraph+S`
// Windows: `Control+Alt+S` or `Control+AltGraph+S` or `AltGraph+S`
},
})
Keybinding Syntax
Keybindings are made up of a sequence of presses.
A press can be as simple as a single key which matches against
KeyboardEvent.code
and
KeyboardEvent.key
(case-insensitive).
// Matches `event.key`:
"d"
// Matches: `event.code`:
"KeyD"
Presses can optionally be prefixed with modifiers which match against any
valid value to
KeyboardEvent.getModifierState()
.
"Control+d"
"Meta+d"
"Shift+D"
"Alt+KeyD"
"Meta+Shift+D"
There is also a special $mod
modifier that makes it easy to support cross
platform keybindings:
- Mac:
$mod
=Meta
(â) - Windows/Linux:
$mod
=Control
"$mod+D" // Meta/Control+D
"$mod+Shift+D" // Meta/Control+Shift+D
Alternatively, you can use parenthesis to use case-sensitive regular expressions to match multiple keys.
"$mod+([0-9])" // $mod+0, $mod+1, $mod+2, etc...
// equivalent regex: /^[0-9]$/
Keybinding Sequences
Keybindings can also consist of several key presses in a row:
"g i" // i.e. "Go to Inbox"
"g a" // i.e. "Go to Archive"
"ArrowUp ArrowUp ArrowDown ArrowDown ArrowLeft ArrowRight ArrowLeft ArrowRight B A"
Each press can optionally be prefixed with modifier keys:
"$mod+K $mod+1" // i.e. "Toggle Level 1"
"$mod+K $mod+2" // i.e. "Toggle Level 2"
"$mod+K $mod+3" // i.e. "Toggle Level 3"
Each press in the sequence must be pressed within 1000ms of the last.
Display the keyboard sequence
You can use the parseKeybinding
method to get a structured representation of a
keyboard shortcut. It can be useful when you want to display it in a fancier way
than a plain string.
import { parseKeybinding } from "tinykeys"
let parsedShortcut = parseKeybinding("$mod+Shift+K $mod+1")
Results into:
[
[["Meta", "Shift"], "K"],
[["Meta"], "1"],
]
Additional Configuration Options
You can configure the behavior of tinykeys in a couple ways using a third
options
parameter.
tinykeys(
window,
{
M: toggleMute,
},
{
event: "keyup",
capture: true,
},
)
options.event
Valid values: "keydown"
, "keyup"
Key presses will listen to this event (default: "keydown"
).
Note: Do not pass
"keypress"
, it is deprecated in browsers.
options.timeout
Keybinding sequences will wait this long between key presses before cancelling
(default: 1000
).
Note: Setting this value too low (i.e.
300
) will be too fast for many of your users.
Top Related Projects
A keyboard input capturing utility in which any key can be a modifier key.
Simple library for handling keyboard shortcuts in Javascript
A simple micro-library for defining and dispatching keyboard shortcuts. It has no dependencies.
A JavaScript library for binding keyboard combos without the pain of key codes and key combo conflicts.
➷ A robust Javascript library for capturing keyboard input. It has no dependencies.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot