Skip to content

Instantly share code, notes, and snippets.

@Luftare
Created October 29, 2017 08:06
Show Gist options
  • Save Luftare/e28b82e5746c57ef15ea59fbef054725 to your computer and use it in GitHub Desktop.
Save Luftare/e28b82e5746c57ef15ea59fbef054725 to your computer and use it in GitHub Desktop.
Input class to capture keyboard and mouse events.
class Input {
constructor(el = document) {
this.keys = [];
this.mouse = [];
this.mousemoveHandlers = [];
this.mousedownHandlers = [];
this.mouseupHandlers = [];
document.addEventListener("keydown", e => {
this.keys[e.key] = true;
});
document.addEventListener("keyup", e => {
this.keys[e.key] = false;
});
el.addEventListener("mousedown", e => {
e.preventDefault();
this.mouse[e.which] = true;
this.mousedownHandlers.forEach(h => h(e))
});
el.addEventListener("mouseup", e => {
this.mouse[e.which] = false;
this.mouseupHandlers.forEach(h => h(e))
});
el.addEventListener("mouseleave", e => {
this.mouse = [];
});
el.addEventListener("mousemove", e => {
this.mousemoveHandlers.forEach(h => h(e))
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment