Scorpion Code
Scorpion Code

Reputation: 119

Run JS code when user finished typing

I have a lot of input fields with the same class. When the user finishes typing the function doneTyping should run.

I tried this but somehow it doesn't work. Can I use one function for all the input fields I have?

$(function() {
  console.log('ready');
  var timer;
  var doneTypingInt = 5000;

  $('.typing').keyup(function(){
      clearTimeout(timer);
      if ($('.typing').val()) {
          timer = setTimeout(doneTyping, doneTypingInt);
      }
  });

  function doneTyping () {
    console.log('function doneTyping');
  }
});

Upvotes: 1

Views: 785

Answers (3)

CryptoBird
CryptoBird

Reputation: 546

I don't think that you have something wrong in your code, you just have to wait 5 seconds to see the result, and in order to use one function for all inputs with the "typing" class, you should use the bind method as follows:

Javascript code: (Jsfiddle)

$(function() {
  console.log('ready');
  var timer;
  var doneTypingInt = 1000;

  $('.typing').keyup(function(){
      clearTimeout(timer);
      if ($('.typing').val()) {
          timer = setTimeout(doneTyping.bind($(this)), doneTypingInt);
      }
  });

  function doneTyping () {
    alert('function doneTyping ' + this.val());
  }
});

Upvotes: 0

ffff
ffff

Reputation: 3070

what you're looking for is debounce

$('.typing').keypress(_.debounce(yourfunc, 3000))

Upvotes: 2

xyiii
xyiii

Reputation: 112

You basically want to use the keypress function. Your adjusted code:

$(function() {
  console.log('ready');
  var timer;
  var doneTypingInt = 5000;

  $('.typing').keypress(function(event){
    if(timer) {
        clearTimeout(timer);
        timer = null;
    }

    timer = setTimeout(doneTyping, doneTypingInt);
  });

  function doneTyping () {
    console.log('function doneTyping');
  }
});

Upvotes: 1

Related Questions