Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery value change event delay

Tags:

jquery

I want to execute a function like 2 seconds after a user has finished typing in the textbox. If they continue to type after 1 second, the delay time is reset back to 2.

It should function something similar to an autocomplete box.

I know of 2 events: change and keyup. The problem I have with change is that the textbox has to loose focus for it to be triggered. for keyup, what if they use the mouse to paste a text?

Could I be helped here?

like image 512
Shawn Mclean Avatar asked May 06 '11 21:05

Shawn Mclean


People also ask

How to delay event in jQuery?

jQuery delay() Method The delay() method sets a timer to delay the execution of the next item in the queue.

How to call function with delay in jQuery?

To call a jQuery function after a certain delay, use the siteTimeout() method. Here, jQuery fadeOut() function is called after some seconds.

How do you delay a function?

To delay a function call, use setTimeout() function. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds. arg1, arg2, arg3 − These are the arguments passed to the function.


1 Answers

There's the HTML5 oninput event, supported by all the current major browsers and can be worked into IE 8 and lower:

$("#myInput").bind("input", function () {     // ... }) 
  • http://whattheheadsaid.com/2010/09/effectively-detecting-user-input-in-javascript (explanation)
  • http://whattheheadsaid.com/projects/input-special-event (plugin)

A very simple cross browser approach would be

$("#myInput").bind("input propertychange", function (evt) {     // If it's the propertychange event, make sure it's the value that changed.     if (window.event && event.type == "propertychange" && event.propertyName != "value")         return;      // Clear any previously set timer before setting a fresh one     window.clearTimeout($(this).data("timeout"));     $(this).data("timeout", setTimeout(function () {         // Do your thing here     }, 2000)); }); 

This would make the event fire twice in IE 9 (one for propertychange, one for input), but it doesn't matter because of the nature of the event handler.

like image 129
Andy E Avatar answered Oct 02 '22 05:10

Andy E