Saturday, March 19, 2011

javascript detect finish typing keystroke delay autocomplete

Okay, the title might be confusing but here is what these about

You want to execute certain function, right after the user has finish its typing

These is different from normal 'keypress' or 'keyup' or 'keydown' event detection because these will execute a function every key is press. Right now you want to give certain delay so that the function only execute at the right time

These is important if you developing an autocomplete (AJAX) because you dont want to execute the script too much. Typing "HELLO" means you do the SQL statement 5 times
H
HE
HEL
HELL
HELLO


But if you do a proper keystroke delay (detect user finish typing) you will only execute the SQL statement once
HELLO


Cut to the story, hopefully understand what I was trying to explain at the top

Here is the function
var typingTimer;
var doneTypingInterval = 700;

//Detect keystroke and only execute after the user has finish typing
function delayExecute()
{
    clearTimeout(typingTimer);
        typingTimer = setTimeout(
        function(){somethingExecuted('typesomethinghere')},
        doneTypingInterval
    );

    return true;
}

function somethingExecuted( theInputName)
{
    alert( "You have type '" + document.getElementById(theInputName).value + "'");
}

//Later in the HTML code, put these
<input onkeypress="return delayExecute();" id="typesomethinghere">

Type something here : (These input id is 'typesomethinghere')
The script will only execute after you finish typing. By assuming when you have stop typing for 0.7 seconds, means you have finish typing

Type something here :
These is what happen if you dont use the script



4 comments:

Ronald said...
This comment has been removed by the author.
Unknown said...

Thanks, just what I was looking for!

Pankaj Kumar said...

thanks

Nico said...

Thank you very much for this piece of code. Really helped me.