Skip to content

Instantly share code, notes, and snippets.

@victorvhpg
Created April 16, 2013 02:48
Show Gist options
  • Save victorvhpg/5392972 to your computer and use it in GitHub Desktop.
Save victorvhpg/5392972 to your computer and use it in GitHub Desktop.
captura/detecta teclas.....
!function(window, document) {
var teclado = {
teclas: {
ESQUERDA: 37,
CIMA: 38,
DIREITA: 39,
BAIXO: 40,
ESPACO: 32
},
teclasPressionadas: {},
estaPressionada: function(keyCode) {
return this.teclasPressionadas[keyCode];
},
pressionaTecla: function(keyCode) {
//LOG("#TECLADO#", "pressionou tecla " + keyCode);
this.teclasPressionadas[keyCode] = true;
},
soltaTecla: function(keyCode) {
// LOG("#TECLADO#", "soltou tecla " + keyCode);
this.teclasPressionadas[keyCode] = false;
},
isTeclaValida: function(keyCode) {
for (var i in this.teclas) {
if (this.teclas[i] === keyCode) {
return true;
}
}
return false;
},
init: function() {
var that = this;
for (var i in this.teclas) {
this.teclasPressionadas[this.teclas[i]] = false;
}
document.addEventListener("keydown", function(e) {
var keyCode = e.which;
if (that.isTeclaValida(keyCode)) {
teclado.pressionaTecla(e.which);
e.preventDefault();
}
});
document.addEventListener("keyup", function(e) {
var keyCode = e.which;
if (that.isTeclaValida(keyCode)) {
teclado.soltaTecla(e.which);
e.preventDefault();
}
});
return this;
}
};
window.teclado = teclado.init();
}(window, window.document);
//exemplo de uso
// if(teclado.estaPressionada(teclado.teclas.DIREITA)){ .... }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment