Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On keypress, when stop after X seconds call function

I have a text input and a textarea and I'm passing the value from the input to the textarea. I am trying to do, when you type something in the input and you stop, after 2 seconds show the values to the textarea.

In this example the textarea gets the input's value instantly:

http://jsfiddle.net/DXMG6/

So i want, when you type and stop, after 2 seconds give the value.

How can I achieve this? I tried to use setTimeout but when the 2 seconds pass, then it keeps getting the value instantly. So basically it works for the first 2 seconds.

like image 758
jQuerybeast Avatar asked Dec 04 '22 18:12

jQuerybeast


2 Answers

You have to reset the timer everytime the user presses the key again:

jQuery(function($){

   function changeFn(){
      alert('Changed');
   } 


   var timer;

   $("#string").bind("keyup", function(){
      clearTimeout(timer);
      timer = setTimeout(changeFn, 2000)
   });

});
like image 137
jantimon Avatar answered Dec 28 '22 22:12

jantimon


Once i made this plugin called bindDelay for jQuery:

$.fn.bindDelay = function( eventType, eventData, handler, timer ) {
    if ( $.isFunction(eventData) ) {
        timer = handler;
        handler = eventData;
    }
    timer = (typeof timer === "number") ? timer : 300;
    var timeouts;
    $(this).bind(eventType, function(event) {
        var that = this;
        clearTimeout(timeouts);
        timeouts = setTimeout(function() {
            handler.call(that, event);
        }, timer);
    });
};

Used like a normal bind method but the last argument is the delay before firing the handler (in mil sec):

 $("input").bindDelay('keyup', function() {
     $("textarea").text( $(this).val() );
 }, 2000);

See fiddle: http://jsfiddle.net/c82Ye/2/

And you unbind and trigger it like normal:

$("input").unbind("keyup");
$("input").trigger("keyup");
like image 38
Andreas Louv Avatar answered Dec 29 '22 00:12

Andreas Louv