JCraine
JCraine

Reputation: 1424

Scoping issues with Jquery slideToggle

I'm using slideToggle and wondering how to pass a variable to the callback function. It traces back undefined. Any ideas? Cheers!

$('.drop-box .button').click(function(){

    var target = $(this).parent();

    var myVar = $(this);    

    target.slideToggle(300, function(myVar){

        alert(myVar); // undefined
    });

    return false;
});

Upvotes: 0

Views: 334

Answers (2)

phuzi
phuzi

Reputation: 13069

As the .slideToggle() doesn't pass any parameters in to the callback you'll have to remove the parameter myVar from your callback's definition. As the callback parameter was hiding your variable the original variable comes back in to scope.

$('.drop-box .button').click(function(){
    var target = $(this).parent();
    var myVar = "hello";    
    target.slideToggle(300, function(){
        alert(myVar); // hello
    });

    return false;
});

Upvotes: 0

Vahe Yepremyan
Vahe Yepremyan

Reputation: 362

Remove myVar from the callback function's arguments. You don't need to pass in the variable, since it is already in scope.

target.slideToggle(300, function() {
    alert(myVar);
});

Upvotes: 2

Related Questions