user2668276
user2668276

Reputation: 59

How can I increment value of the variable when scroll reaches top of the div

I have 5 div on the same page and the same class name="post". Also I got one variable name p = 1.

What I want to do is when I scroll div1, it should increase p value by +1 means p=2 now for div1.

Then if I scroll div2 , it should increase p value by +1 means p=2 now for div2. etc. If I scroll div2 again, p value must be p=3.

If I scroll div4, p value must be 2 and again if I scroll div1, p value was 2 last time. Now it must be 3.

But what really happening when I scroll div1, p becomes p=2. Then if I scroll any div p becomes p=3, if I scroll again it becomes p=4.

So I want to do is when I scroll any divs in any order it should increase the value of 'p' separately according that div. In other word I just want to count how many times I scroll all 5 divs individually.

Here is my JS Fiddle, and the JS code follows:

$("window").load()
{
    $('.post').scrollTop($('.post').height())  
}



var p=1;
$('.post').scroll(function() {


        if($(this).scrollTop()==0)
        {
            p++;
            alert(p);


        }

});

Upvotes: 1

Views: 1377

Answers (1)

Bruno Calza
Bruno Calza

Reputation: 2780

You can use the data api to save the data individually

$("window").load(){
    $('.post').scrollTop($('.post').height()).data('p',0); //initialize
}


$('.post').scroll(function() {
    var $this = $(this);

    if($this.scrollTop() == 0){
        $this.data('p',$this.data('p') + 1); //increment
        alert($this.data('p'));
    }  
});

See working JSFiddle

Upvotes: 1

Related Questions