0

I have some elements on my page, i want to call a function over them by JQuery extended function. I have this function declarement:

(function ($) {
        $.fn.enable = function (delay) {
            console.log(delay); //logs 3000
            setTimeout(function (elem) {
                console.log(elem);
                elem.css("opacity", "1");
            }(this), delay);
            return this;
        };
    })(jQuery);

as you know, which declares a enable function over JQuery objects. now when i call something like this:

$("#start").enable(3000);

the function enable runs, but the code inside function (elem)... runs immediately instead of running after a while!

How and Why??

Hamed Zakery Miab
  • 738
  • 2
  • 12
  • 34
  • 1
    If you end your anonymous function with `(this)` you're passing in it's return value, not the function. – sje397 Sep 27 '14 at 09:07

1 Answers1

3

That is because you are calling the function "function(elem)" instead of providing it as an arguement. Try this

(function ($) {
        $.fn.enable = function (delay) {
            console.log(delay); //logs 3000
             var elem = this;
            setTimeout(function () {
                console.log(elem);
                elem.css("opacity", "1");
            }, delay);  //you should not call a function here
            return this;
        };
    })(jQuery);
wallop
  • 2,510
  • 1
  • 22
  • 39