Skip to content

Instantly share code, notes, and snippets.

@davalapar
Created August 19, 2018 06:53
Show Gist options
  • Save davalapar/bf883924a449ae1a9b242263208fd95d to your computer and use it in GitHub Desktop.
Save davalapar/bf883924a449ae1a9b242263208fd95d to your computer and use it in GitHub Desktop.
Keylock.js
/* eslint-disable no-undef */
// http://keycode.info
class Keylock {
constructor(key) {
this.keyCode = key.charCodeAt(0);
this.isDown = false;
this.isUp = true;
this.onPress = undefined;
this.onRelease = undefined;
window.addEventListener(
'keydown', this.downHandler.bind(this), false,
);
window.addEventListener(
'keyup', this.upHandler.bind(this), false,
);
}
downHandler(event) {
if (event.keyCode === this.keyCode) {
if (this.isUp === true && typeof this.onPress === 'function') {
this.onPress();
}
this.isDown = true;
this.isUp = false;
}
event.preventDefault();
}
upHandler(event) {
if (event.keyCode === this.keyCode) {
if (this.isDown === true && typeof this.onRelease === 'function') {
this.onRelease();
}
this.isDown = false;
this.isUp = true;
}
event.preventDefault();
}
setOnPress(parameter) {
if (typeof parameter === 'function') {
this.onPress = parameter;
}
return this;
}
setOnRelease(parameter) {
if (typeof parameter === 'function') {
this.onRelease = parameter;
}
return this;
}
}
export default Keylock;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment