Especially when building more complex UI’s, it is helpful or even necessary to provide the user with keyboard shortcuts. 
Of course this is also conceivable in video games or something like that. Anyway — here is Mousetrap with just 2.2kB for you

Get the code, for example from a CDN: https://craig.global.ssl.fastly.net/js/mousetrap/mousetrap.min.js?a4098
Import it in the <head> of your website. 
Or:
npm install mousetrap
import Mousetrap from ‘mousetrap’

Let’s have a look on a few examples

Bind a single Key:

Mousetrap.bind(‘4’, function() {
console.log(‘you pressed 4’)
})

Important note: It makes a difference whether it is a capital or small letter that was defined or pressed. For Mousetrap, for example, x is not equal to X.

Bind a single key, trigger the function when you let the key come up, after holding it down. (Because of the keyup-setting)

Mousetrap.bind(‘x’, function() {
console.log(‘You pressed x and let it come up’)
},‘keyup’)

Trigger when the a, b and c keys are pressed in sequence. The specified sequence must be observed.

Mousetrap.bind(‘a b c’, function() { 
console.log(‘You pressed a, then b & after that you pressed c’)
})

Creating a key combination

Mousetrap.bind(‘command+shift+k’, function(e) {
console.log(‘you pressed command, shift & k’)
})

Several key combinations, which should be reacted to in the same way, can be passed with an array

Mousetrap.bind([‘a+d’, ‘w+s’], function(e) {
console.log(‘you pressed a & d OR w & s’)
})

For more, check out the official documentation 🙂


0 commenti

Lascia un commento

Segnaposto per l'avatar