Gaddiel Sadoc Peralta
Gaddiel Sadoc Peralta

Reputation: 331

Jquery: functions using the same global variable messing with my code

Based on this awnser: How can I determine the direction of a jQuery scroll event?

I did a function like this:

tempScrollTop=0;
$.fn.cool = function(options){
    windowTop = $(window).scrollTop(); 

    if (tempScrollTop < windowTop ){
        //scroll down
    }
    else if (tempScrollTop > windowTop ){
        //scroll up
    }

    tempScrollTop = windowTop;
};

but each time I try to use my function

 $(window).scroll(function(e) {
    $("#element1").cool();
    $("#element2").cool();
 }

$("#element2") takes the global variable tempScrollTop already modified by $("#element1") and for element 2 tempScrollTop and windowTop has the same value, so my function doesn't work.

Any ideas on what can I do? I dont want to create n functions one for each element.

Upvotes: 0

Views: 425

Answers (2)

Christophe
Christophe

Reputation: 28154

It seems that what you actually want to do is:

$("#element1","#element2").cool();

Then in your cool function:

tempScrollTop=0;
$.fn.cool = function(options){
windowTop = $(window).scrollTop(); 

if (tempScrollTop < windowTop ){
    //scroll down
    this.each(function() {
        // do stuff with each selected element $(this)
    });
}
else if (tempScrollTop > windowTop ){
    //scroll down
    this.each(function() {
        // do stuff with each selected element $(this)
    });
}

tempScrollTop = windowTop;
};

More info on plugin authoring here.

Another way would be to separate the scroll calculation from the action on the elements:

$(window).scroll(function(e) {
    var scrollDiff=calculateScroll();
    $("#element1").cool(scrollDiff);
    $("#element2").cool(scrollDiff);
}

Upvotes: 1

Michael Malinovskij
Michael Malinovskij

Reputation: 1422

var tempScrollTop = 0,
    innerScrollTop;
    $.fn.cool = function(options){
        var $this = $(this);
        innerScrollTop = $this.data('scrollTop') || tempScrollTop;

        windowTop = $(window).scrollTop();

        if (innerScrollTop <= windowTop ){
            //scroll down
        } else {
            //scroll up
        }

        $this.data('scrollTop', windowTop);
    };

Upvotes: 0

Related Questions