Adman
Adman

Reputation: 335

jQuery - Need to use variable from first function inside another function?

Uber Noob but I thought I was close.

var markers = $j('span.marker');

$j(markers).each(function () { //function to store original marker positions 
    var startOrigin = $j(this).css('margin-left');

});

$j("a.timeline-view").click(function () { //function to return markers to stored positions
    $j(markers).each(function () {

        $j(this).animate({
            marginLeft: startOrigin
        })

    });
});

Second function can't find the var??

Upvotes: 0

Views: 2767

Answers (2)

Tom Tu
Tom Tu

Reputation: 9593

I assume that $j == alias to jquery

The solution to your problem is using the jquery .data('name', val) to store the value bound to an element and then retrieve it with .data('name') when necessary.

$j(markers).each(function(){ //function to store original marker positions 

       $j(this).data('startOrigin', $j(this).css('margin-left'));

});

$j("a.timeline-view").click( function() { //function to return markers to stored positions
    $j(markers).each(function(){
        var marker = $j(this);
        marker.animate({marginLeft : marker.data('startOrigin') })
    });         
});

check http://api.jquery.com/jQuery.data/ for more info on using jQuery data

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 237865

To explain why your code doesn't work...

A function in Javascript has in scope all variables that were declared in containing functions or in that function. Using the var keyword sets a variable to the current scope. In your example, startOrigin is only in the scope of the first function. If you put it in the parent scope, all the functions in your example will have it in their scope:

var markers = $j('span.marker');
var startOrigin;  // declare the variable in this scope

markers.each(function () { //function to store original marker positions 
    startOrigin = $j(this).css('margin-left'); // use the parent scope
});

$j("a.timeline-view").click(function () { //function to return markers to stored positions
    markers.each(function () {

        $j(this).animate({
            marginLeft: startOrigin // use parent scope
        })

    });
});

Note, however, that this example is kind of broken anyway. You are looping through the whole set of markers, overwriting the startOrigin each time. You need to use data as Tom Tu said in his answer to set data for an individual DOM element.

Upvotes: 1

Related Questions