Etienne Dupuis
Etienne Dupuis

Reputation: 13796

Passing parameters within a jQuery function fails .fadeOut()

Im trying to pass parameters to myFunction, but it seems to be causing issues because it is inside a jQuery function. Any tips?

//this works fine
myFunction(1);

//this doesn't work fine!
$('myObj').fadeOut(1000, myFunction(1));

Upvotes: 0

Views: 755

Answers (3)

fengd
fengd

Reputation: 7579

you need to pass the reference of the function

$('myObj').fadeOut(1000, myFunction);

but the callback function isn't sent any parameter, so you'll need to set your parameter somewhere else. e.g.:

var time = 1;
function myFunction(){
    time += 1 // do anything you want with the parameter
}

Upvotes: 0

Rob Kielty
Rob Kielty

Reputation: 8162

From http://api.jquery.com/fadeOut/

If you’d like to send arguments to your callback function, you may define a new anonymous function that calls your parameterized function. For example:

var pageUrl = generateNextPageUrl(); $(“#content”).fadeOut(1000, function () { refreshContent(pageUrl) });

Without the anonymous function definition, my suposed callback was called immediatly (sic) without waiting to finish the fadeout effect.

Upvotes: 0

ninja
ninja

Reputation: 2263

Might be a bit excessive, but did you try calling the function in the callback?

$('myObj').fadeOut(1000, function() {
    myFunction(1);
});

Upvotes: 1

Related Questions