Add Custom Keyboard Shortcuts To Webpage - keymap.js

File Size: 9.05 KB
Views Total: 1566
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Add Custom Keyboard Shortcuts To Webpage - keymap.js

keymap.js is a simple yet powerful jQuery plugin for capturing keyboard events and binding custom hotkeys and/or cheat codes to your webpage. 

Supports single key or key combinations. The goal of this plugin is to simplify the task of binding custom event handlers to JavaScript keyboard events.

How to use it:

1. Insert the JavaScript keymap.js after loading the latest jQuery library.

<script src="/path/to/cdn/jquery.min.js"></script>
<script src="/path/to/jquery.keymap.js"></script>

2. The old school fashion to create Keyboard Shortcuts on the page:

$(element).on('keydown', event => {
  if (event.key == 'C'){
    // do something when pressing C
  }
});

$(element).on('keydown', event => {
  if (event.key == 'C' && event.altKey){
    // do something when pressing ALT+C
  }
});

3. With jQuery keymap.js, you're able to define your Keyboard Shortcut in a JS object and pass it as the second parameters to keyboard events as follows:

$(element).on('keydown', {
  keys: 'C'
}, event => {
  // do something when pressing C
});

$(element).on('keydown', {
  keys: 'alt-c'
}, event => {
  // do something when pressing ALT+C
});

4. The plugin also supports handling a key sequence, which means that you can add a cheatcode (like Konami Code) or an Easter egg to the webpage.

$(element).on('keydown', {
  keys: 'A A B B'
}, event => {
  // do something
});

Changelog:

2020-09-04

  • use strict

2020-08-07

  • Bugfix

This awesome jQuery plugin is developed by dwachss. For more Advanced Usages, please check the demo page or visit the official website.