jQuery $(this) inside function

user1324762 picture user1324762 · Aug 15, 2012 · Viewed 13.6k times · Source

I want to pass $(this) to function but I am not sure. There is one similar thread, but I still can not make it working. I hope somebody can help me.

$(document).ready(function() {
  var delay = (function(){
    var timer = 0;
    return function(callback, ms){
      clearTimeout (timer);
      timer = setTimeout(callback, ms);
    };
  })();

  $('input').keyup(function() {
      delay(function(){
        alert($(this).val());
      }, 1000 );
  });
});

Answer

Harmen picture Harmen · Aug 15, 2012

You should save a reference to this :

$('input').keyup(function() {
    var $this = $(this);
    delay(function(){
      alert($this.val());
    }, 1000 );
});

Another option is to re-bind this to the function:

  $('input').keyup(function() {
      delay(function(){
        alert($(this).val());
      }.bind(this), 1000 );
  });