They perform different functions.
onkeydown
is the first to fire and we can stop it. If you have an input you can prevent the pressed key from typing in the input if you have an associated event handler.
onkeypress
is the second to fire. Note that this event is not triggered 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 dropped and its input added / registered in the DOM. In the case of an input the new character is inserted and can not cancel, that is, an input will receive the character.
Examples:
keydown
An input that ignores vowels: link
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 fine print: link
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 m
small and
keydown | 77 | M |
keypress | 77 | M |
no M
big.
keyup
Adding fields: link
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 background runs a script with every keyup
and sums the values of all inputs in a field with the total.