Question:
When exactly are they fired? And what are the usage contexts for each one?
I ask this because of all the times I needed to use it, it always solved only with onkeyup
. Although the doubt is in javascript
it reflects in other languages as well.
Answer:
They fulfill different functions.
onkeydown
is the first to fire and we can stop him. If you have an input you can prevent the pressed key from writing to the input if you have an associated event handler.
onkeypress
is the second to fire. Note that this event is not fired on keys that do not generate characters, such as F1 ~ F12, tab, esc, etc. Note that keypress
generates different results for large and small print.
onkeyup
is triggered when the key is released and its input added/registered in the DOM. In the case of an input, the new character is inserted and you cannot cancel it, that is, an input will receive the character.
Examples:
keydown
An input that ignores vowels: http://jsfiddle.net/4t4ta4q5/
var input = document.querySelector('input');
var ignorar = ['a', 'e', 'i', 'o', 'u'];
input.addEventListener('keydown', function (e) {
var char = e.keyCode || e.which;
var letra = String.fromCharCode(char).toLowerCase();
if (ignorar.indexOf(letra) != -1) e.preventDefault();
});
keypress
Distinguish large print from small print: http://jsfiddle.net/awrjLphp/
function log(e) {
var char = e.code || e.keyCode || e.which;
var res = [e.type, char, String.fromCharCode(char), '<br />'].join(' | ');
document.getElementById('res').innerHTML += res;
};
input.addEventListener('keydown', log);
input.addEventListener('keypress', log);
This code will give
keydown | 77 | M |
keypress | 109 | m |
when we press the small m
and
keydown | 77 | M |
keypress | 77 | M |
in M
great.
keyup
Add fields: http://jsfiddle.net/gz2ttyt1/
var inputs = $$('body > input').addEvent('keyup', function (e) {
var numerico = this.value.replace(/[^0-9\.]/g, '');
if (!numerico) this.value = this.value.slice(0, -1);
var soma = inputs.map(function (input) {
return parseFloat(input.value) || 0;
}).reduce(function (a, b) {
return a + b;
}, 0);
$$('body div > input').set('value', soma);
});
This is MooTools code, but in the end it runs a script at each keyup
and adds up the input values all in a field with the total.