Search code examples
javascriptjquerythis-pointer

jQuery $(this) inside function


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 );
  });
});

Solution

  • 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 );
      });