Ziik
Ziik

Reputation: 1049

jQuery - setTimeout function with $(this) in a plugin

My problem is somehow relatid to the question here. I'm trying to do a plugin which shows a message and after that fades it out.

Here is the plugin:

(function($) {
$.fn.showWarning = function(msg) {
    return this.each(function() {
        $(this).text(msg).show().hide(); // <-preloads message
        $(this).fadeIn('fast', function() {
            $(this).stop().text(msg);
            setTimeout(function() {
                $(this).fadeOut(300);
            }, 2500);
        });
    });
};
})(jQuery);

and the whole code is here: http://jsfiddle.net/e5kns/6/

The problem is that the message doesn't disappear, so I suppose it has something ti do with setTimeout. Maybe $(this) isn't referencing where it should?

Firebug gives:

a.ownerDocument is undefined

And Chrome:

Uncaught TypeError: Cannot read property 'defaultView' of undefined

Upvotes: 1

Views: 846

Answers (2)

labroo
labroo

Reputation: 2961

Try this,

(function($) {
    $.fn.showWarning = function(msg) {
        return this.each(function() {
            $(this).text(msg).show().hide(); // <-preloads message
            $(this).fadeIn('fast', function() {
                $this = $(this);
                $(this).stop().text(msg);
                setTimeout(function() {
                    $this.fadeOut(300);
                }, 2500);
            });
        });
    };
})(jQuery);

ps: As @Esailija recommends, dealy and fadeout is better

Upvotes: 1

Esailija
Esailija

Reputation: 140228

You could

$(this).stop().text(msg).delay(2500).fadeOut(300)


And indeed, this isn't referencing anything other than window. Because the browser is calling the timeout callback with this set to window. this is only based on how a function is called.

setTimeout($.proxy(function() {
    $(this).fadeOut(300);
}, this), 2500);

Would fix that because it generates another function that discards this and uses the provided this and explicitly applies that to your original function.

Upvotes: 3

Related Questions