Adding Keyboard Shortcuts To Your Website With Mousetrap

There are many websites which offers keyboard shortcuts for performing various actions. You can take the example of Facebook and Gmail for this. Few blogs also offer post navigation via left and right arrow keys. If you also want to add keyboard shortcuts in your website, you can try adding it with jQuery. No, you do not need to do it manually if you can do it easily with Plugin. Mousetrap is a nice jQuery plugin which lets you easily add keyboard shortcuts in your application. There is nothing complicated in this.
Use of the plugin is very simple. You only need to include JS file and then add JS functions to use. If you want to test in offline, you can download from here.
<script src="//cdnjs.cloudflare.com/ajax/libs/mousetrap/1.4.6/mousetrap.min.js"></script>
After including this you can bind keyboard shortcut in any key by using the code below. Below code uses bind that binds a specified keyboard command to a callback function.
Mousetrap.bind('a', function(e) { // your action function here... });
You can also use sequence of keys to perform an action like below:
Mousetrap.bind('a s', function(e) { // your action function here... });
You can also try multiple key combinations like this:
Mousetrap.bind('ctrl+s', function(e) { // Your action function here });
You can also bind multiple Keyboard shortcuts to perform same action by using the code below:
Mousetrap.bind(['ctrl+s', 'command+s'], function(e) {
// Your action function here
});
Now it depends on you how to use. You can use action code as per your need. You can also call other function via keyboard shortcuts by using the code similar to below code.
function search() { var search = $('#search'); search.focus(); } Mousetrap.bind('CTRL+F', search);
BROWSER SUPPORT
Mousetrap has been tested in following browsers.
- Internet Explorer 6+
- Safari
- Firefox
- Chrome
Leave a comment
Comment policy: We love comments and appreciate the time that readers spend to share ideas and give feedback. However, all comments are manually moderated and those deemed to be spam or solely promotional will be deleted.