gitmyhub

mousetrap

JavaScript ★ 12k updated 3y ago

Simple library for handling keyboard shortcuts in Javascript

Mousetrap is a tiny 2 KB JavaScript library with no dependencies that adds keyboard shortcuts to any web page, supporting single keys, combinations like Ctrl+K, and multi-key sequences like Gmail shortcuts.

JavaScriptsetup: easycomplexity 1/5

Mousetrap is a small JavaScript library that lets you add keyboard shortcuts to a web page. When someone presses a key or key combination, Mousetrap triggers whatever action you specify, whether that is opening a menu, navigating to a section, or running any custom behavior.

The library weighs around 2 kilobytes when compressed, so it loads quickly without noticeably slowing down your page. It has no dependencies on other frameworks or libraries, which means it fits into any web project regardless of what tools you are already using. It has been tested in browsers going back to Internet Explorer 6 as well as modern browsers like Chrome, Firefox, and Safari.

You can listen for single key presses, key combinations such as Control+K or Command+Shift+K, or sequences of keys typed one after another. Sequences follow the same pattern as Gmail keyboard shortcuts, where typing two letters in order triggers a specific action. The README even shows the Konami code, a long sequence of directional keys, bound to a callback as a demo of what is possible. You can also trigger key events from code programmatically, not just from user input.

Setting it up involves adding a script tag to your page, then calling Mousetrap.bind() with the key or combination you want and a function to run when it is pressed. The library handles differences between operating systems and keyboard layouts automatically. You can bind multiple combinations to the same action at once, which is useful when Mac users press Command+K and Windows users press Control+K to do the same thing.

The project is open source under the Apache 2.0 license and the full documentation is available on the author's site.

Where it fits