Web Design Forum: Quickly checking that a key was pressed in an input - Web Design Forum

Jump to content

WDF
WDF Premium Memberships Reseller Hosting
-----
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:

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.
0
 

0 Comments On This Entry

Recent Entries

Recent Comments

May 2012

S M T W T F S
  12345
6789101112
13141516 17 1819
20212223242526
2728293031