Events "keypress" "keydown" "keyup"

4

I want a certain function to be executed when I press a key, whatever. But let it run once (at the moment you press it). I expected to do this with "keydown" but behaves the same "keypress"

addEvent(document, "keypress", function (e) {
    console.log("keypress");
});
addEvent(document, "keydown", function (e) {
    console.log("keydown");
});
addEvent(document, "keyup", function (e) {
    console.log("keyup");
});

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;
    }
}

PS: The documentation regarding the addEvent function is in this question

    
asked by Theia 30.06.2017 в 22:40
source

3 answers

5

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;
    }
}
    
answered by 30.06.2017 / 22:52
source
2

First of all keyPress is not equal to KeyDown

KeyPress = KeyDown + KeyUp

   |    KeyDown     ^     KeyUp 
   v                |            KeyPress
|Tecla|          |Tecla|

To understand it better let's see what happens when the user does not release the key

   |    KeyDown    |     KeyDown     |    KeyDown    ^     KeyUp 
   v               v                 v               |            KeyPress
|Tecla|         |Tecla|           |Tecla|         |Tecla|

;(function(global)
{
  "use strict"
  function myKeyUp(e)
  {
       console.log("Key up")
  }
  
  function myKeyDown(e)
  {
      console.log("Key down")
  }
  
  function myKeyPress(e)
  {
      console.log("Key Press")
  }
  
  var input = document.getElementsByTagName('input')[0]
  input.onkeyup = myKeyUp
  input.onkeydown = myKeyDown
  input.onkeypress = myKeyPress
}(window))
<input type="text" placeholder="Escribe aquí"></input>

It is worth mentioning that the correct functioning of keyPress depends mainly on the widget toolkit adjacent to it, if the previous code does not work, just make the following fix

;(function(global)
{
"use strict"
	var miAPI = new function()
	{
		var keyup = false
		
		this.makeKeyUp = function(fn)
		{
			return function(e){
				var auxEv
				fn.call(null, e)
				keyup = true
				auxEv = new KeyboardEvent('keypress', e)
				e.target.dispatchEvent(auxEv) 
			}
		}

		this.makeKeyDown = function(fn)
		{
			return function(e)
			{
				fn.call(null, e)
				keyup = false
			}
		}

		this.makeKeyPress = function(fn)
		{
			return function(e)
			{
				if (keyup) {
					fn.call(null , e)
				}
			}
		}

	}

  function myKeyUp(e)
  {
       console.log("Key up")
  }
  
  function myKeyDown(e)
  {
      console.log("Key down")
  }
  
  function myKeyPress(e)
  {
      console.log("Key Press")
  }
  
  
  var input = document.getElementsByTagName('input')[0]
  input.onkeyup = miAPI.makeKeyUp(myKeyUp)
  input.onkeydown = miAPI.makeKeyDown(myKeyDown)
  input.onkeypress = miAPI.makeKeyPress(myKeyPress)
}(window))
<input type="text" placeholder="Escribe aquí"></input>
    
answered by 01.07.2017 в 00:26
2

Use the property KeyboardEvent.repeat , as well You will know if you are pressing the same key for a long time:

input = document.querySelector('input');

input.addEventListener('keypress', e => {
  if(e.repeat){
    e.preventDefault();
    return;
  }
  // Lógica aquí
  console.log('keypress ' + String.fromCharCode(e.which || e.keyCode))
});

input.addEventListener('keyup', e =>{
  console.log('keyup');
})
<input type="text">
    
answered by 04.07.2017 в 22:46