0

The below code inside setTimeout doesn't work whereas same code without setTimeout works perfectly fine

var size_disabled_input = 0;

$('#txtUSLead , #txtmy').on("mouseover", function () {
size_disabled_input = $(this).css('width');
if ((this.value.length) > 8) 
{
$(this).css('cssText', 'width: ' + ((this.value.length + 1) * 7) + 'px !important');
}
});

$('#txtUSLead, #txtmy').on("mouseout", function () {
setTimeout(function (){
$(this).css('cssText', 'width: ' + size_disabled_input + 'px !important');
}, 2000);
})
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • Have a look at http://stackoverflow.com/questions/2130241/pass-correct-this-context-to-settimeout-callback – 0x6C77 Sep 09 '14 at 16:04

1 Answers1

1

Within the setTimeout function this will not refer to the button that you are in.

So, you can use the bind method:

$('#txtUSLead, #txtmy').on("mouseout", function () {
    setTimeout(function () {
        $(this).css('cssText', 'width: ' + size_disabled_input + 'px !important');
    }.bind(this), 2000);
})

Or, use a variable to store the this value:

$('#txtUSLead, #txtmy').on("mouseout", function () {
    var that = $(this);
    setTimeout(function () {
        that.css('cssText', 'width: ' + size_disabled_input + 'px !important');
    }, 2000);
})

Or, you can use the proxy() method in jQuery:

$('#txtUSLead, #txtmy').on("mouseout", function () {
    setTimeout($.proxy(function() {
        $(this).css('cssText', 'width: ' + size_disabled_input + 'px !important');
    }, this), 2000);
})
Paul T. Rawkeen
  • 3,994
  • 3
  • 35
  • 51
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • Thanks !!! You nailed it! I was getting this as undefined in console log but couldnt identify it referrign to window object in there – user3814961 Sep 09 '14 at 16:31
  • Sorry but what do you mean by strict mode or normal mode ? Also the solutions you gave , it is cross compatible with all the browsers right? I used the bind method – user3814961 Sep 09 '14 at 16:35