Quick Tip: Add Keyboard Shortcuts To Your Web App

Quick Tip: Add Keyboard Shortcuts To Your Web App

We power users love our keyboard shortcuts. We use them everywhere – in our code editor, in Photoshop, in gmail. And we hate it when we hit Ctrl+S in a web app, only to see our browser offering to download it. Adding shortcuts to your application is not hard at all. In this quick tip, we will show you how to do it, by using Mousetrap.js.

1. Single Keys

Single keys are easy. You can do it with a simple event listener for keypress on the document object. But with Mousetrap, it is even better.

After hitting the run button, focus the editor by clicking on it. Otherwise, it won’t register your key presses and the demo won’t work.

// This is the standard Mousetrap.js syntax.
// The parameters are the symbol we expect and a callback function.
Mousetrap.bind('7', function() { console.log('7'); showBalloon(7); });
Mousetrap.bind('/', function() { console.log('/'); showBalloon('/'); }, 'keyup');
Mousetrap.bind('esc', function() { console.log('escape'); showBalloon('Escape'); }, 'keyup');

// The code below is for our demo.
// Displays a balloon with info on every successful button press. 
var balloon = $('.keyboard-answer'),
    stopTimeout;

$(document).click(function(){
  if(balloon.is(':visible')) {
    balloon.removeClass('active');
  }
});

function showBalloon(data) {
  balloon.addClass('active').find('h3 span').text(data);

  clearTimeout(stopTimeout);
  stopTimeout = setTimeout(function () {
    balloon.removeClass('active');
  }, 1500);
}
<div class="content">

    <ul>
      <li>Try pressing <a class="button c55"><span class="key">7</span></a></li>
      <li>Or you can try hitting <a class="button c191"><span class="key">/</span></a></li>
      <li>Even special keys work <a class="button c27 fn esc"><span class="key">esc</span></a></li>
    </ul>
    
    <div class="keyboard-answer">
      <h3>You pressed <span></span></h3>
    </div>  

</div>      

2. Alternative Symbols

Mousetrap shines when listening for more complex key combinations like capital letters and special symbols.

// Mousetrap.js can listen for symbols and not actual keys presses,
// so any alternative symbol can be bound (the ones reached by pressing shift + key)
Mousetrap.bind('@', function() { console.log('@'); showBalloon('@'); });
Mousetrap.bind('M', function() { console.log('M'); showBalloon('M'); });
Mousetrap.bind('>', function() { console.log('>'); showBalloon('>'); });

// The code below is for our demo.
// Displays a balloon with info on every successful button press. 
var balloon = $('.keyboard-answer'),
    stopTimeout;

$(document).click(function(){
  if(balloon.is(':visible')) {
    balloon.removeClass('active');
  }
});

function showBalloon(data) {
  balloon.addClass('active').find('h3 span').text(data);

  clearTimeout(stopTimeout);
  stopTimeout = setTimeout(function () {
    balloon.removeClass('active');
  }, 1500);
}
<div class="content">

    <ul>
      <li>You can type in symbols like <a class="button c50"><span class="key">@</span></a></li>
      <li>Also capital letters<a class="button c77"><span class="key">m</span></a></li>
      <li>And any other alternative character<a class="button c190"><span class="key">&gt;</span></a></li>
    </ul>
    
    <div class="keyboard-answer">
      <h3>You pressed <span></span></h3>
    </div>  

</div>      

3. Key combinations

Combinations that involve the Control key are equally easy (see the next example for how to listen for both Control and the OS X Command key).

// To bind button combos, use '+' to request as many keys as you want.
// This way, all the keys have to be pressed at once.
Mousetrap.bind('ctrl+s', function(){ console.log('save'); showBalloon('Ctrl + S'); return false; });
// Returning false works just like e.preventDefault() and stops the usual functionality of the hotkeys.
Mousetrap.bind('ctrl+z', function(){ console.log('undo'); showBalloon('Ctrl + Z'); return false; });
Mousetrap.bind('ctrl+shift+z', function(){ console.log('redo'); showBalloon('Ctrl + Shift + Z'); return false; });

// The code below is for our demo.
// Displays a balloon with info on every successful button press. 
var balloon = $('.keyboard-answer'),
    stopTimeout;

$(document).click(function(){
  if(balloon.is(':visible')) {
    balloon.removeClass('active');
  }
});

function showBalloon(data) {
  balloon.addClass('active').find('h3 span').text(data);

  clearTimeout(stopTimeout);
  stopTimeout = setTimeout(function () {
    balloon.removeClass('active');
  }, 1500);
}
<div class="content">

    <ul>
      <li>
        Try hitting the <strong>Save</strong> hotkeys <a class="button c17 control"><span class="key">control</span></a> +
        <a class="button c83"><span class="key">s</span></a>
      </li>
      <li>
        The <strong>Undo</strong> command <a class="button c17 control"><span class="key">control</span></a> +
        <a class="button c90"><span class="key">z</span></a>
      </li>
      <li>
        Or the <strong>Redo</strong> command <a class="button c17 control"><span class="key">control</span></a> +
        <a class="button c16 shiftleft"><span class="key">Shift</span></a> +
        <a class="button c90"><span class="key">z</span></a>
      </li>
    </ul>
    
    <div class="keyboard-answer">
      <h3>You pressed <span></span></h3>
    </div>  

</div>      

4. Multiple Combinations

Passing an array instead of a string lets you listen for multiple key combinations at once. This is useful when you have to listen for combinations which involve the Control (for Windows and Linux) and Command (for Mac) keys.

// By listing different combinations with a comma
// you can set the same function to be called on different bindings.
Mousetrap.bind(['command+k', 'ctrl+k'], function() {
  console.log('command + k or control + k');
  showBalloon('Command + K or Control + K');
});

// The code below is for our demo.
// Displays a balloon with info on every successful button press. 
var balloon = $('.keyboard-answer'),
    stopTimeout;

$(document).click(function(){
  if(balloon.is(':visible')) {
    balloon.removeClass('active');
  }
});

function showBalloon(data) {
  balloon.addClass('active').find('h3 span').text(data);

  clearTimeout(stopTimeout);
  stopTimeout = setTimeout(function () {
    balloon.removeClass('active');
  }, 1500);
}
<div class="content">

    <ul>
      <li>Two different key combinations
        <a class="button command commandleft"><span class="key">command</span></a> +
        <a class="button c75"><span class="key">k</span></a>
      </li>
      <li>Can have the same functionality
        <a class="button c17 control"><span class="key">control</span></a> +
        <a class="button c75"><span class="key">k</span></a>
      </li>
    </ul>
    
    <div class="keyboard-answer">
      <h3>You pressed <span></span></h3>
    </div>  

</div>      

5. Sequences

This type of shortcuts are very powerful, and are used in apps like gmail. Works with array keys as well!

// Listing different symbols and keys with just an empty space between them
// will cause Moustrap.js to bind them as a sequence.
// This way they have to be pressed one after another in this specific order.
Mousetrap.bind('g i', function() { console.log('go to inbox'); showBalloon('Go To Inbox Command'); });
Mousetrap.bind('up left down left down down right right enter', function() {
  console.log('konami code');
  showBalloon('Konami Code');
});

// The code below is for our demo.
// Displays a balloon with info on every successful button press. 
var balloon = $('.keyboard-answer'),
    stopTimeout;

$(document).click(function(){
  if(balloon.is(':visible')) {
    balloon.removeClass('active');
  }
});

function showBalloon(data) {
  balloon.addClass('active').find('h3 span').text(data);

  clearTimeout(stopTimeout);
  stopTimeout = setTimeout(function () {
    balloon.removeClass('active');
  }, 1500);
}
<div class="content">

    <ul>
      <li>Press keys one after another <a class="button c71"><span class="key">g</span></a><a class="button c73"><span class="key">i</span></a></li>
      <li>Perfect for easter eggs
        <a class="button c38 arrows"><span class="key">⬆</span></a>
        <a class="button c37 arrows"><span class="key">⬅</span></a>
        <a class="button c38 arrows"><span class="key">⬇</span></a>
        <a class="button c37 arrows"><span class="key">⬅</span></a>
        <a class="button c40 arrows"><span class="key">⬇</span></a>
        <a class="button c40 arrows"><span class="key">⬇</span></a>
        <a class="button c39 arrows"><span class="key">➡</span></a>
        <a class="button c39 arrows"><span class="key">➡</span></a>
        <a class="button c13 alt enter"><span class="key">enter</span></a>
      </li>

    </ul>
    
    <div class="keyboard-answer">
      <h3>You entered the <span></span></h3>
    </div>  

</div>      

Conclusion

This was our quick tip on keyboard shortcuts. If you’ve used keyboard hotkeys before, or are brave enough to experiment with them in your next project, do share the results with us in the comments below.

Presenting Bootstrap Studio

a revolutionary tool that developers and designers use to create
beautiful interfaces using the Bootstrap Framework.

Learn more
Web Browser Frame DevKit Box Mouse Cursor
by Nick Anastasov

Nick is a JavaScript programmer who loves Node and all things HTML5. He is interested in photography and is the resident food expert at Tutorialzine's office.

1Share this post
2Read one more article
3Get your free book
Book Cover
jQuery Trickshots

Tutorialzine's advanced jQuery techniques book.

Download

2 Comments

  1. Dan Kaufman says:

    Awesome tut and totally what I was looking for for a project I'm working on right now!
    Thank you so much for including a section on Mac command keys and Win control keys, too! I'm using node.js to package a HTML5/CSS/JS desktop app and this was the missing piece, especially with my app being cross-platform this adds the perfect usability touch.

  2. Fizzix says:

    This is excellent! Its also not used often, but some times its so useful. 9GAG is a good example site that uses this. Its makes the interface so much easier to use.

Add Comment

Add a Reply

HTML is escaped automatically. Surround code blocks with <pre></pre> for readability.
Perks:   **bold**   __italics__   [some text](http://example.com) for links