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 p开发者_如何学编程roblem 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?
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.
You can bind the input
event and also keyup
for fallback on older browsers. You can then start a timer, which gets reset every time a user action is detected. By saving the timer handle in the current element's data makes sure multiple elements don't interfere with each other.
$('input').bind('input keyup', function(){
var $this = $(this);
var delay = 2000; // 2 seconds delay after last input
clearTimeout($this.data('timer'));
$this.data('timer', setTimeout(function(){
$this.removeData('timer');
// Do your stuff after 2 seconds of last user input
}, delay));
});
You can put on both change and keyup:
var globalTimeout;
$(function() {
$("#myInput").change(initTimer).keyup(initTimer);
});
function initTimer() {
if (globalTimeout) clearTimeout(globalTimeout);
globalTimeout = setTimeout(handler, 2000);
}
function handler() {
...
}
I'd do it like this:
$("selector").keyup(function(){
if(typeof(window.delayer) != 'undefined')
clearTimeout(window.delayer);
window.delayer = setTimeout(function_you_want_to_get_execute_with_delay, 2000);
});
Cheers
keyup
will work:
$("#s").keyup(function(e){
$("#t").html($(this).val());
});
Jsfiddle: http://jsfiddle.net/3nx6t/
精彩评论