I want a certain function to be executed when I press a key, any key. But let it run once (the moment you press it). I expected to do this with "keydown" but it behaves the same as "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 found in this question
According to this documentation :
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 pressed.
You could do something like this:
onKeyUp() will be executed when the key is "released" , that is, when the user stops pressing it . For example:
Look what happens now if we use onKeyDown() , write something in the text box:
According to what you indicated in the comments (that it only executes once) , I think you could use something like this:
First of all
keyPress
it's not the same asKeyDown
KeyPress = KeyDown + KeyUp
To understand it better, let's see what happens when the user does not release the key
It is worth mentioning that the correct functioning of keyPress depends mainly on the toolkit widget adjacent to it, if the previous code does not work, just do the following fix
Use the property
KeyboardEvent.repeat
, so you'll know if you're pressing the same key for too long: