2

I'm calling an anonymous function:

        closeSidebar(function() {
            alert("function called");
            $(this).addClass("current");
            setTimeout(function(){openSidebar()}, 300);
        });

But $(this) doesn't work as expected and I need to pass it as an argument into the function. After a bit of research I thought this would work:

            closeSidebar(function(el) {
               $(el).addClass("current");
               setTimeout(function(){openSidebar()}, 300);
            })(this);

But it doesn't. How do I add arguments to an anonymous function?

jsFiddle - Click a button on the right, it animates in then calls the function above. When the button has the class "current" it will have a white bar on the left side of the button but the class never changes.

3 Answers 3

5

You can refer below code for passing parametrs in anonymous function.

var i, img;
for(i = 0; i < 5; i++)
{
  img = new Image();
  img.onload = function(someIndex)
  {
    someFunction(someIndex);
  }(i);
  img.src = imagePaths[i];
}

Hope u will get some idea.

Sign up to request clarification or add additional context in comments.

Comments

4

You can also do this:

        closeSidebar(function(el) {
            $(el).addClass("current");
            setTimeout(function(){openSidebar()}, 300);
        }(this));

The arguments need to be passed to the anonymous function itself, not the caller.

1 Comment

This is valid syntax? And here I thought closeSidebar(function (el) {} (this)); would at best call the function and pass its return to closeSidebar.
1

Use this method for adding arguments:

var fn=function() { };
fn.apply(this,arguments);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.