Home:ALL Converter>Event handling issue in JavaScript

Event handling issue in JavaScript

Ask Time:2012-09-17T16:50:07         Author:Ranjan Sarma

Json Formatter

There is a textbox which is associated with an onkeyup event listener (a JavaScript function, say that alerts something). For an example-

<input type='text' name='text1' onkeyup='exec(this.value);'/>
exec = function(textdata) { alert(textdata); }

In this case the alert message will come each time the user hits something on the keyboard.

Is there any way of even handling, where in the event handler will proceed only after a few seconds of inactivity. that is, in this case the alert message will come only if the user has done typing a long text, and is thinking if he wants to add something more or not. For example, he types in his first name and waits for 2 second and after that the alert message appears, and alert message does not appears while he types in each letter of his first name.

Author:Ranjan Sarma,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/12455862/event-handling-issue-in-javascript
Mark Walters :

You need to use onkeyup rather than onchange if you wish to run a function every time a key is pressed. Try this for the functionality you want\n\n<input type='text' name='text1' onkeyup='exec(this.value);'/>\n<script>\n\nvar timer; //This needs to be a global variable\n\nexec = function(textData){\n\n clearTimeout(timer);\n\n timer = setTimeout(function(){ alert(textData) }, 2000); \n}\n</script>\n\n\nEvery time the user presses a key (enters a character into the textbox) the function is called and the timer is cleared. The timer is then set to alert the textbox's value after 2 seconds, if they again press any keys before the 2 seconds has elapsed the timer is reset. Here is a working jsFiddle.",