Simple library for handling keyboard shortcuts in Javascript

Overview

Mousetrap

CDNJS

Mousetrap is a simple library for handling keyboard shortcuts in Javascript.

It is licensed under the Apache 2.0 license.

It is around 2kb minified and gzipped and 4.5kb minified, has no external dependencies, and has been tested in the following browsers:

  • Internet Explorer 6+
  • Safari
  • Firefox
  • Chrome

It has support for keypress, keydown, and keyup events on specific keys, keyboard combinations, or key sequences.

Getting started

  1. Include mousetrap on your page before the closing </body> tag

    <script src="/path/to/mousetrap.min.js"></script>

    or install mousetrap from npm and require it

    var Mousetrap = require('mousetrap');
  2. Add some keyboard events to listen for

    <script>
        // single keys
        Mousetrap.bind('4', function() { console.log('4'); });
        Mousetrap.bind("?", function() { console.log('show shortcuts!'); });
        Mousetrap.bind('esc', function() { console.log('escape'); }, 'keyup');
    
        // combinations
        Mousetrap.bind('command+shift+k', function() { console.log('command shift k'); });
    
        // map multiple combinations to the same callback
        Mousetrap.bind(['command+k', 'ctrl+k'], function() {
            console.log('command k or control k');
    
            // return false to prevent default browser behavior
            // and stop event from bubbling
            return false;
        });
    
        // gmail style sequences
        Mousetrap.bind('g i', function() { console.log('go to inbox'); });
        Mousetrap.bind('* a', function() { console.log('select all'); });
    
        // konami code!
        Mousetrap.bind('up up down down left right left right b a enter', function() {
            console.log('konami code');
        });
    </script>

Why Mousetrap?

There are a number of other similar libraries out there so what makes this one different?

  • There are no external dependencies, no framework is required
  • You are not limited to keydown events (You can specify keypress, keydown, or keyup or let Mousetrap choose for you).
  • You can bind key events directly to special keys such as ? or * without having to specify shift+/ or shift+8 which are not consistent across all keyboards
  • It works with international keyboard layouts
  • You can bind Gmail like key sequences in addition to regular keys and key combinations
  • You can programatically trigger key events with the trigger() method
  • It works with the numeric keypad on your keyboard
  • The code is well documented/commented

Tests

Unit tests are run with mocha.

Running in browser

View it online to check your browser compatibility. You may also download the repo and open tests/mousetrap.html in your browser.

Running with Node.js

  1. Install development dependencies

    cd /path/to/repo
    npm install
  2. Run tests

    npm test

Documentation

Full documentation can be found at https://craig.is/killing/mice

Comments
  • Prevent repeat events from holding a key

    Prevent repeat events from holding a key

    Feature request:

    If I bind a callback to, say, the A key, and then I hold down the A key, the callback will be called many times, rapidly, until I release the A key.

    It would be nice to have an option to have such a callback only fire once.

    opened by bblack 20
  • Add Mousetrap.record() method to capture and return keyboard sequences

    Add Mousetrap.record() method to capture and return keyboard sequences

    Strangely enough, I decided I wanted something like this at almost the same time as @evitolins (see #109).

    You said you'd prefer this as an extension; but I figured it couldn't hurt to submit the pull request and see what you think. I also added a little tester to your 'peanut butter' UI.

    opened by dtao 17
  • Allow binding shortcut keys with a scope

    Allow binding shortcut keys with a scope

    I'd be interested in using this, but I need some sort of "scoping", i.e. hotkeys would dispatch differently based on what element is highlighted.

    feature 
    opened by tych0 14
  • Wrapping specific elements

    Wrapping specific elements

    I've wanted this for a while: adding the ability for Mousetrap to target specific elements rather than the entire document. This is really useful if, e.g., you want to provide keyboard shortcuts to a specific <textarea> or an element with the contenteditable attribute, but don't want these shortcuts to affect the rest of the document.

    I've made the change backwards compatible with the way the library works by default. I.e., Mousetrap.bind() still works at the document level. To handle keyboard shortcuts only bubbling from from a specific element, you use wrap():

    Mousetrap.wrap(element).bind('sequence', callback);
    

    I kind of wanted the API like this:

    Mousetrap(element).bind('sequence', callback);
    

    ...but that would have involved more code.

    I know it looks like a big diff, but that's mainly because of the indentation changes. To see a cleaner diff, you can use git diff --ignore-space-change.

    opened by dtao 12
  • Add generic `mod` alias for command/ctrl

    Add generic `mod` alias for command/ctrl

    Add a generic mod modifier, which is an alias for command on OS X, and ctrl everywhere else.

    mod might not be the best name for it, so I'm open to suggestions.

    opened by bobthecow 12
  • Adding Auto-Generated Help Lightbox on ? Press

    Adding Auto-Generated Help Lightbox on ? Press

    I've added an awesome feature that automatically creates a lightbox with the keyboard shortcuts currently registered and is bound to ?. It looks pretty much the same as gmail's lightbox.

    lightbox_screenshot

    I've basically added a few "public" methods to show, hide and toggle this help and bound ? on start and on reset. A user can still override it. I achieve this by injecting the CSS (only if invoked) to the start of the head declaration and than injecting a div that implements a simple lightbox with a title and div table. The lightbox shows all the shortcuts, and if available an explanation, which is either specified by a new fourth argument to bind (ye, kinda hacky I know) or if none taking the name of the callback function.

    The CSS is injected to be the first child of the head directive to allow people to override the styling of the lightbox and all the other elements. Basic documentation for this is here: https://github.com/Sveder/mousetrap/wiki/Help-Overlay-CSS-Style-Overriding

    opened by Sveder 12
  • International keyboard layouts do not work correctly

    International keyboard layouts do not work correctly

    I tried the examples on demo page using standard Turkish (Q) layout, but some of them didn't work. (Namely, '$' and '*'.)

    Now I tried them again and somehow made them work. $ character is typed using AltGr+4 combination, but it didn't work with it or the US variant Shift+4; however it works for AltGr+Shift+4.

    On the other hand, asterisk character has a seperate key for itself on Turkish layout. But it also doesn't work. It works by combining Turkish and US layouts and pressing AltGr+Shift+8 --and followed by 'a', of course, for the example to work.

    bug 
    opened by frontsideair 12
  • Define a ctrl/command string

    Define a ctrl/command string

    Define a key which is valid for either ctrl or command key presses, so it can be used either in PC or Mac. Instead of ['command+k', 'ctrl+k'], it could be 'comctrl+k'

    task 
    opened by davoclavo 11
  • Use Mousetrap in Gmail (website with many iframes?)

    Use Mousetrap in Gmail (website with many iframes?)

    I'm trying to add a custom shortcut in gmail through a chrome extension.

    Without Mousetrap one can add a keydown in every iframe as described here: http://stackoverflow.com/questions/9424550/how-can-i-detect-keyboard-events-in-gmail

    This works fine. However if I use the same approach and do

    Mousetrap.bind('4', function() { alert('343'); });
    

    It's not working. I suspect this is because Mousetrap will only add the eventlistner to the toplevel document.

    Any pointers?

    opened by janmechtel 10
  • Synthesizes key down on modifier up

    Synthesizes key down on modifier up

    On my browser (Chrome 20.0.1132.47 on Fedora 17) and a US keyboard:

    1. Browse to the demo at http://craig.is/killing/mice
    2. Press and hold the shift key
    3. Press and hold the '4' key
    4. The "$" item correctly illuminates
    5. Release the shift key. The "4" item incorrectly illuminates. "4" was never typed.
    bug 
    opened by andyross 9
  • _belongsTo error due to element being null

    _belongsTo error due to element being null

    Hi,

    I'm developing some features on an app, and I have them working on Chrome, but now I am testing on Firefox I am getting an error.

    The issue seems to be in the _belongsTo() function which is recursive. After several iterations, it calls itself with the element parameter as null - ie element.parentNode is null.

    I've not figured out what is wrong, but I am suspecting it is something to do with the webcomponents implementation of shadow-dom - or lack thereof - that is certainly one significant difference between chrome and firefox, and since thie _belongsTo() function seems to be ascending the DOM tree, then perhaps it is related.

    It'd be great to get some opinion of how this problem can be worked-around.

    In the meantime, I'll see if I can reduce my code into a simple test case.

    Thanks,

    Max.

    webcomponentsjs#0.5.2 mousetrap#1.5.2 polymer#0.5.5

    stack trace :

    console.trace(): debugger eval code:1 _belongsTo() mousetrap.js:421 _belongsTo() mousetrap.js:421 _belongsTo() mousetrap.js:421 _belongsTo() mousetrap.js:421 _belongsTo() mousetrap.js:421 _belongsTo() mousetrap.js:421 Mousetrap.prototype.stopCallback() mousetrap.js:970 _fireCallback() mousetrap.js:601 Mousetrap/self._handleKey() mousetrap.js:666 Mousetrap.prototype.handleKey() mousetrap.js:983 _handleKeyEvent() mousetrap.js:726 invoke() webcomponents.js:1070 dispatchBubbling() webcomponents.js:1024 dispatchEvent() webcomponents.js:998 dispatchOriginalEvent() webcomponents.js:953

    opened by davidmaxwaterman 8
  • Add a function that allows us to remove the event listeners

    Add a function that allows us to remove the event listeners

    Right now, there is no way to remove event listeners which can lead to memory leaks. This will create a function that will remove the event listeners.

    opened by jarmit 0
  • Are there any alternatives to mousetrap?

    Are there any alternatives to mousetrap?

    mousetrap is basically an abandoned project. Lots of unsolved issues and unmerged pull requests. I want to know are there any better alternatives? Thanks.

    opened by 0x7FFFFFFFFFFFFFFF 1
  • Shortcuts that are a combination (f+i) are saved under the second key - if there is a collision in that second key, the callbacks can misfire

    Shortcuts that are a combination (f+i) are saved under the second key - if there is a collision in that second key, the callbacks can misfire

    Example: I have two shortcuts: i which will navigate my page and f+i which will add a new item to the page. If I just press i while selected on an item on the page, it will match with the f+i shortcut because that is saved under the self._callbacks[i] even though it is a combination.

    opened by milemons 1
  • ev.which is readonly and hence should not be assigned during normalization.

    ev.which is readonly and hence should not be assigned during normalization.

    https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/which image

    https://github.com/ccampbell/mousetrap/blob/2f9a476ba6158ba69763e4fcf914966cc72ef433/mousetrap.js#L721

                if (typeof e.which !== 'number') {
                    e.which = e.keyCode;
                }
    

    should becomes something like

    const charCode = (typeof e.which == "number") ? e.which : e.keyCode;
    

    and charCode should be passed to methods later instead of using e.which everywhere.

    opened by fa93hws 0
  • Use of navigator.platform invokes Chrome issue

    Use of navigator.platform invokes Chrome issue

    Chrome is showing an "issue" because Mousetrap uses navigator.platform which they plan to remove support for in the future.

    More information in this link https://blog.chromium.org/2021/05/update-on-user-agent-string-reduction.html

    Suggestion for fix https://web.dev/user-agent-client-hints/

    Screenshot of issue image

    opened by omundy 0
  • ctrl+tab doesn't fire

    ctrl+tab doesn't fire

    I want to use ctrl+tab in my electronjs app. So it is not a browser to interrupt with tab changing shortcut. However when I'm inside a text area it doesn't fire at all. Other shortcuts without tab do. How do I bind the whole document ?

    <script>
        Mousetrap.bind(['command+tab', 'ctrl+tab'], function() {
           alert('command tab or control tab);
    
            // return false to prevent default browser behavior
            // and stop event from bubbling
            return false;
        });
    </script>
    
    opened by donnydarko 1
Releases(1.6.5)
  • 1.6.5(Jan 23, 2020)

  • 1.6.4(Jan 23, 2020)

  • 1.6.3(Mar 4, 2019)

  • 1.6.2(Jun 2, 2018)

  • 1.6.1(Apr 2, 2017)

  • 1.6.0(May 29, 2016)

    • Updated to not fail when included in server side environments
    • Added Mousetrap.addKeycodes method for adding custom keyCodes not defined in the existing map
    Source code(tar.gz)
    Source code(zip)
  • 1.5.3(Jul 2, 2015)

  • 1.5.2(Mar 30, 2015)

  • 1.5.1(Mar 28, 2015)

    Two quick things

    • Defaults target element to document if you just call new Mousetrap() on its own
    • Checks against document first in the _belongsTo function to improve performance
    Source code(tar.gz)
    Source code(zip)
  • 1.5.0(Mar 28, 2015)

    This release is long overdue. It brings a bunch of stuff.

    • Adds support for creating multiple instances of Mousetrap

    • Adds support for binding Mousetrap events to specific elements on the page (for example forms or form fields)

      For more information see http://craig.is/killing/mice#wrapping

    • Adds support for using Mousetrap as a common js module

    • Improves handling of + key in keyboard commands. Also adds an alias to reference + as plus to avoid confusion

    • General code formatting clean up

    One note about backwards compatibility

    If you are using any of the plugins in the plugins directory and you update to Mousetrap 1.5.0 they will break. You have to install the new versions of the plugins. This is because all the public functions are now bound to the Mousetrap prototype instead of being attached to the global object.

    Source code(tar.gz)
    Source code(zip)
  • 1.4.6(Nov 14, 2013)

  • 1.4.4(Jul 3, 2013)

  • 1.4.3(Jul 3, 2013)

    • Fix issue where keypress event could break sequence if next expected event is keypress #140
    • Fix issue where spacebar could break sequences
    Source code(tar.gz)
    Source code(zip)
  • 1.4.2(Jul 3, 2013)

⌨ Awesome handling of keyboard events

No Longer Actively Maintained If someone would like to take over maintainence, feel free to get in touch (@keithamus on twitter). I'll happily transfe

Keith Cirkel 1.2k Dec 6, 2022
A JavaScript library for binding keyboard combos without the pain of key codes and key combo conflicts.

KeyboardJS KeyboardJS is a library for use in the browser (node.js compatible). It Allows developers to easily setup key bindings. Use key combos to s

Robert Hurst 2k Dec 30, 2022
A keyboard input capturing utility in which any key can be a modifier key.

Keypress Version 2.1.5 Keypress is a robust keyboard input capturing Javascript utility focused on input for games. For details and documentation, ple

David Mauro 3.2k Dec 28, 2022
jQuery Hotkeys lets you watch for keyboard events anywhere in your code supporting almost any key combination.

jQuery.Hotkeys #About jQuery Hotkeys is a plug-in that lets you easily add and remove handlers for keyboard events anywhere in your code supporting al

John Resig 2.6k Jan 2, 2023
A simple library for handling keyboard shortcuts with Alpine.js.

✨ Help support the maintenance of this package by sponsoring me. Alpine.js Mousetrap A simple library for handling keyboard shortcuts with Alpine.js.

Dan Harrin 102 Nov 14, 2022
A simple micro-library for defining and dispatching keyboard shortcuts. It has no dependencies.

keymaster.js Keymaster is a simple micro-library for defining and dispatching keyboard shortcuts in web applications. It has no dependencies. It’s a w

Thomas Fuchs 6.5k Jan 4, 2023
Obsidian plugin to add keyboard shortcuts commonly found in code editors such as Visual Studio Code or Sublime Text

Code Editor Shortcuts This Obsidian plugin adds keyboard shortcuts (hotkeys) commonly found in code editors such as Visual Studio Code or Sublime Text

Tim Hor 143 Dec 30, 2022
Obsidian plugin to support a sequenced of keyboard shortcuts to run commands.

Sequence Shortcuts (Obsidian plugin) This plugin allows you to use a sequences of chords for shortcuts instead of single chords. Creating a hotkey You

Ruan Moolman 23 Dec 17, 2022
Browser extension to add more keyboard shortcuts to TweetDeck.

TweetDeck Shortcut Plus Browser extension to add more keyboard shortcuts to TweetDeck. Keyboard shortcuts Browse Browse tweet (default: alt+b) Browse

Ryo Nakamura 5 May 26, 2022
Browser extension to add more keyboard shortcuts to twitter.com.

Twitter Shortcut Plus Browser extension to add more keyboard shortcuts to twitter.com. Keyboard shortcuts Browse Browse links in background (default:

Ryo Nakamura 6 Jun 4, 2022
⌨ Awesome handling of keyboard events

No Longer Actively Maintained If someone would like to take over maintainence, feel free to get in touch (@keithamus on twitter). I'll happily transfe

Keith Cirkel 1.2k Dec 6, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Remote Keyboard Tutoring System is a web-based system that can be attached to any keyboard synthesizer through a MIDI connector.

The Remote Keyboard Tutoring System is a web-based system that can be attached to any (electronic) keyboard synthesizer through a MIDI connector. Once our system is connected to the keyboard, the user can interactively learn, play or teach in combination with the web application that we provide.

Department of Computer Engineering, University of Peradeniya 3 Nov 15, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A simple, lightweight JavaScript API for handling browser cookies

JavaScript Cookie A simple, lightweight JavaScript API for handling cookies Works in all browsers Accepts any character Heavily tested No dependency S

null 20.2k Jan 3, 2023
Pressure is a JavaScript library for handling both Force Touch and 3D Touch on the web

Pressure is a JavaScript library for handling both Force Touch and 3D Touch on the web, bundled under one library with a simple API that makes working with them painless.

Stuart Yamartino 2.9k Dec 29, 2022
Obsidian plugin: Type text shortcuts that expand into javascript generated text.

Obsidian Plugin - Text Expander JS (open beta) This Obsidian plugin allows the user to type text shortcuts that are replaced by (or "expanded into") j

Jon Heard 79 Dec 27, 2022
A JavaScript library for binding keyboard combos without the pain of key codes and key combo conflicts.

KeyboardJS KeyboardJS is a library for use in the browser (node.js compatible). It Allows developers to easily setup key bindings. Use key combos to s

Robert Hurst 2k Dec 30, 2022
A JavaScript library for binding keyboard combos without the pain of key codes and key combo conflicts.

KeyboardJS KeyboardJS is a library for use in the browser (node.js compatible). It Allows developers to easily setup key bindings. Use key combos to s

Robert Hurst 2k Dec 30, 2022