According to this documentation :
These events are generated when the user presses the keys.
The onKeyDown event happens when the user presses a key.
The onKeyUp event occurs when the user stops pressing a key.
The onKeyPress event is generated when a key is held down.
If what you need is to associate an event for when you press a key, what you should use is onKeyDown () , since this is the one that is executed when a key is pressed , but not when it is held down .
You could do something like this:
addEvent(document, "keydown", function (e) {
console.log("Se presiono una tecla");
});
function addEvent(element, eventName, callback) {
if (element.addEventListener) {
element.addEventListener(eventName, callback, false);
} else if (element.attachEvent) {
element.attachEvent("on" + eventName, callback);
} else {
element["on" + eventName] = callback;
}
}
onKeyUp () will run when the key is "released" ", that is when the user stops pressing . As for example:
function cambiaMayuscula(elemento){
elemento.value = elemento.value.toUpperCase();
}
<input type="text" onkeyup="cambiaMayuscula(this)" placeholder="Escribe algo...">
See what happens now if we use onKeyDown () , write something in the text box:
function cambiaMayuscula(elemento){
elemento.value = elemento.value.toUpperCase();
}
<input type="text" onkeydown="cambiaMayuscula(this)" placeholder="Escribe algo...">
In this function we convert the text written by the user to
MAYUSCULA, but look what happens when you write.
According to what you tell me in the comments (only run once) , I think you could use something like this:
var teclaPresionada = false;
addEvent(document, "keydown", function (e) {
if(!teclaPresionada){
console.log("Tecla Presionada");
teclaPresionada = true;
}
});
addEvent(document, "keyup", function (e) {
if(teclaPresionada){
console.log("Tecla Liberada");
teclaPresionada = false;
}
});
function addEvent(element, eventName, callback) {
if (element.addEventListener) {
element.addEventListener(eventName, callback, false);
} else if (element.attachEvent) {
element.attachEvent("on" + eventName, callback);
} else {
element["on" + eventName] = callback;
}
}