A los usuarios avanzados nos encantan los atajos de teclado. Los usamos en todos lados: en nuestro editor de código, en Photoshop, en Gmail… Y odiamos cuando hacemos Ctrl+S en una aplicación web, y nos aparece el típico popup de navegador para indicarnos que si queremos descargarnos la página web. Añadir atajos de teclado en nuestra aplicación no es muy difícil. En este sencillo artículo, te mostrarmos cómo llevarlo a cabo utilizando la librería Mousetrap.js
Teclas únicas
Implementar atajos de teclas únicas es muy fácil. Puedes hacerlo con un event listener cuando se presione una tecla en el objeto del documento. Pero con Mousetrap es mucho más sencillo.
El HTML
<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>
El Javascript
// 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'); } });
Caracteres alternativos
A Mousetrap se le da especialmente bien tratar con atajos de teclado más complejos como letras mayúsculas y caracteres especiales.
El HTML
<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">></span></a></li>
</ul>
<div class="keyboard-answer">
<h3>You pressed <span></span></h3>
</div>
</div>
El Javascript
// 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); }
Combinaciones de teclas
Las combinaciones que implican la tecla Control son igual de fáciles (échale un ojo al siguiente ejemplo que te muestra cómo detectar la tecla CTrl y la tecla X como un atajo)
El HTML
<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>
El Javascript
// 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); }
Múltiples combinaciones
Pasar un array en lugar de una cadena, te permite detectar múltiples combinaciones de teclas a la vez. Esto es útil cuando hay que detectar combinaciones que impliquen la tecla Ctrl (para Windows y Linux) y Command (Mac).
El HTML
<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>
El Javascript
// 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); }
Secuencias
Este tipo de atajos de teclados son muy poderosos, y se utilizan en aplicaciones como Gmail. Funciona con un array de teclas tal que así:
El HTML
<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>
El Javascript
// 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); }
Fuente: tutorialzine.com