Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <span id="log">press key</span>
</body>
</html>
 
#log {
  margin: 20px;
  padding: 20px;
  border: 2px solid red;
  display: inline-block;
}
 
const keyboard = (function () {
  const _units = [];
  document.addEventListener('keydown', evt => {
    let idx = _units.length;
    const keyCode = evt.keyCode;
    while (idx--) {
      if (_units[idx].codes.includes(keyCode)) {
        _units[idx].handle(evt);
      }
    }
  });
  // Export
  return {
    map: {
      tab: 9,
      esc: 27 // etc
    },
    register(keys, handle) {
      // Переводим в коды
      const codes = keys.map(key => this.map[key.toLowerCase()]
                         || key.toUpperCase().charCodeAt(0));
      
      _units.push({codes, handle});
    }
  }
})();
// Регистрируем обработчик
keyboard.register(['a', 'b', 'tab'], (evt) => {
  console.log(evt);
  log.innerHTML = evt.keyCode;
});
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers