user3814961 user3814961 - 1 month ago 13
jQuery Question

css change inside setTimeout doesn't work

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

Answer

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