I just found a quick-and-easy trick when you're binding events to inputs.
If you've got an input and you which to bind functionality to it (say an auto-suggestion list or a username check), you probably don't want the functionality to fire every time a key is pressed. Otherwise users will press the shift key or a cursor key, it could get bandwidth-heavy. I was starting to check which key was pressed to ensure that a letter, number or symbol was entered:
... but that if statement started to get really big taking into account all possible symbols, the delete key, backspace etc. Instead, a simple solution just occurred to me - keep track of the length:
Et voila, a simple, easy-to-remember way to save yourself some processing.
If you've got an input and you which to bind functionality to it (say an auto-suggestion list or a username check), you probably don't want the functionality to fire every time a key is pressed. Otherwise users will press the shift key or a cursor key, it could get bandwidth-heavy. I was starting to check which key was pressed to ensure that a letter, number or symbol was entered:
document.getElementById('input').onkeyup = function (e) {
if (e.which === 8 || (e.which <= 65 && e.which >= 90)) {
functionality();
}
};... but that if statement started to get really big taking into account all possible symbols, the delete key, backspace etc. Instead, a simple solution just occurred to me - keep track of the length:
var input = document.getElementById('input'),
len = input.value.length;
input.onkeyup = function (e) {
var currentLength = this.value.length;
if (currentLength !== len) {
len = currentLength;
functionality();
}
};Et voila, a simple, easy-to-remember way to save yourself some processing.
Help













