Tiny & Robust Keyboard Shortcut Solution For JavaScript – Mousetrap

Category: Javascript , Recommended | May 17, 2023
Author:ccampbell
Views Total:24 views
Official Page:Go to website
Last Update:May 17, 2023
License:Apache 2.0

Preview:

Tiny & Robust Keyboard Shortcut Solution For JavaScript – Mousetrap

Description:

Mousetrap is a powerful, simple JavaScript library to manage keyboard shortcuts in web applications. You can bind keys, combinations of modifier keys like Ctrl and Alt with regular keys, and even full key sequences.

It can be used to bind keyboard shortcuts to any JavaScript function, such as opening a help window, submitting a form, or even triggering an Easter egg (like Konami Code) in your app.

How to use it:

1. Download and include the Mousetrap library on the page.

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

2. Create your own shortcuts using the Mousetrap.bind method. The third parameter is used to specify the type of keyboard event (‘keypress’, ‘keydown’, or ‘keyup’) to trigger the function.

// single key
Mousetrap.bind('s', function(){
  alert('You just pressed S')
});
// combination of keys
Mousetrap.bind('ctrl+s', function(){
  alert('You just pressed ctrl+s')
});
// sequence of keys
Mousetrap.bind('a b c',  function(){
  alert('You just pressed a, b, c')
}, 'keydown');

3. Trigger the function manually.

Mousetrap.trigger('s');

4. Unbind specific shortcuts.

Mousetrap.unbind('s');
Mousetrap.unbind('s', 'keyup');

5. Remove all shortcuts.

Mousetrap.reset();

6. Enable the shortcuts in text fields using the mousetrap class.

<textarea name="message" class="mousetrap"></textarea>

7. Or using the Global bindings plugin. A keyboard event bound using Mousetrap.bind will only work outside of form input fields, but using Moustrap.bindGlobal will work in both places.

<script src="plugins/global-bind/mousetrap-global-bind.min.js"></script>
Mousetrap.bindGlobal('ctrl+s', function() {
  // do something
});

8. Overwrite the default bind behavior and allows you to bind multiple combinations in a single bind call. You can optionally pass in keypress, keydown or keyup as a second argument.

<script src="plugins/bind-dictionary/mousetrap-bind-dictionary.min.js"></script>
Mousetrap.bind({
  'a': function() { console.log('a'); },
  'b': function() { console.log('b'); }
});

9. Enable Mousetrap to be paused and unpaused without having to reset keyboard shortcuts and rebind them.

<script src="plugins/pause/mousetrap-pause.min.js"></script>
// stop Mousetrap events from firing
Mousetrap.pause();
// allow Mousetrap events to fire again
Mousetrap.unpause();

10. Use Mousetrap to record keyboard sequences and play them back.

<script src="plugins/record/mousetrap-record.min.js"></script>
// stop Mousetrap events from firing
Mousetrap.pause();
// allow Mousetrap events to fire again
Mousetrap.unpause();

You Might Be Interested In:


Leave a Reply