Javascript library for capturing keyboard input – HotKeys.js

A robust Javascript library for capturing keyboard input and key combinations entered. It has no dependencies. Try to press your keyboard, The following button will highlight. HotKeys.js is an input capture library with some very special features, it is easy to pick up and use, has a reasonable footprint (~3kb) (gzipped: 1.73kb), and has no dependencies. It should not interfere with any JavaScript libraries or frameworks.

Install

Install Plugin via NPM

$ npm install hotkeys-js --save



Libraries

Add the ‘hotkeys.js’ script to the webpage.

<script src="https://unpkg.com/hotkeys-js/dist/hotkeys.min.js"></script>

JS

Basic usage

<script type="text/javascript">
hotkeys('ctrl+a,ctrl+b,r,f', function(event,handler) {
  switch(handler.key){
    case "ctrl+a":alert('you pressed ctrl+a!');break;
    case "ctrl+b":alert('you pressed ctrl+b!');break;
    case "r":alert('you pressed r!');break;
    case "f":alert('you pressed f!');break;
  }
});
</script>




Advanced usages.

hotkeys('a', function(event,handler){
    //event.srcElement: input 
    //event.target: input
    if(event.target === "input"){
        alert('You just pressed a!')
    }
    alert('You just pressed a!') 
});
 
hotkeys('ctrl+a,ctrl+b,r,f', function(event,handler){
    switch(handler.key){
        case "ctrl+a":alert('You just pressed ctrl+a!');break;
        case "ctrl+b":alert('You just pressed ctrl+b!');break;
        case "r":alert('You just pressed r!');break;
        case "f":alert(' You just pressedf!');break;
    }
});
 
hotkeys('ctrl+r', function(){ alert('Alert!'); return false });
 
hotkeys('⌘+r, ctrl+r', function(){ });

API REFERENCE

hotkeys('*', function(e){
  if(hotkeys.shift) console.log('shift is pressed!');
  if(hotkeys.ctrl) console.log('ctrl is pressed!');
  if(hotkeys.alt) console.log('alt is pressed!');
  if(hotkeys.option) console.log('option is pressed!');
  if(hotkeys.control) console.log('control is pressed!');
  if(hotkeys.cmd) console.log('cmd is pressed!');
  if(hotkeys.command) console.log('command is pressed!');
});

See live demo and download source code.

DEMO | DOWNLOAD

This awesome plugin is developed by jaywcjlove. Visit their official github repository for more information and follow for future updates.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.