David Horák
David Horák

Reputation: 5565

How in jQuery pass parameters into function after function fadeOut

Hi how i can pass variable into this function

var _index = $("#sideNewsContent_menu li").index($(this)) + 1;

$("#sideNewsContent_body").fadeOut(300, function (index) {

     //HERE i want to use variable _index
});

Upvotes: 4

Views: 2535

Answers (2)

Jerome WAGNER
Jerome WAGNER

Reputation: 22442

you could use the fact the "_index" can be used in the closure that you are defining :

var _index = $("#sideNewsContent_menu li").index($(this)) + 1;
$("#sideNewsContent_body").fadeOut(300, function () {
 alert(_index);
});

In javascript, when you define an anonymous function (a closure), you can use all the variables that exist in the current context (except "this" which is a special keyword).

Upvotes: 4

Matt
Matt

Reputation: 75327

It's already in the scope. Just be sure not to put var _index anywhere in the function, or it'll create a local variable called _index, which will take precedence over the _index variable in the closure.

var _index = $("#sideNewsContent_menu li").index($(this)) + 1;

$("#sideNewsContent_body").fadeOut(300, function (index) {

     _index++;

     alert(_index);
});

Don't do this:

$("#sideNewsContent_body").fadeOut(300, function (index) {

     var _index = _index++;

     alert(_index);
});

Upvotes: 1

Related Questions