Charas
Charas

Reputation: 1817

Javascript function inside if statement still runs even though condition is not met

I am trying to make that when a user scroll till a certain point (1250px from the top), the script will run a function "just ONCE", then when the user scroll more till another 1250px from the point before (2500px from the top), the script will run the function again ONCE.

However, my script keeps running the function after 1250 px, which I already added another 1250 to var current_post, so at this point, var current_post should be 2500, and if the var offset is at 1600, the function should not run, but it is keep running.

Javascript

$(window).scroll(function() {
    var offset = $(window).scrollTop();
    var current_pos = 1250;

    if(offset > current_pos) {
        current_pos += 1250;
        //do some function
   }
});

Please help me spot my mistake and correct my understanding of this.. Thx in advance.

Upvotes: 0

Views: 1924

Answers (3)

Marcos Pérez Gude
Marcos Pérez Gude

Reputation: 22158

Just put out the variable:

var current_pos = 1250;
$(window).scroll(function() {
    var offset = $(window).scrollTop();

    console.log(offset);
    if(offset > current_pos) {
       current_pos += 1250;
        //do some function
        console.log(current_pos);
     }
 });

http://jsfiddle.net/sq32f7h8/

Upvotes: 0

musefan
musefan

Reputation: 48415

The problem is that each time the event is being fired, you are setting the current_pos back to 1250. So you never get to use the updated value.

Try setting the current_pos variable outside of the event handler, so it doesn't get re-assigned to 1250 with each event.

var current_pos = 1250;
$(window).scroll(function() {
    var offset = $(window).scrollTop();

    if(offset > current_pos) {
        current_pos += 1250;
        //do some function
   }
});

Upvotes: 2

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

Place var current_pos=1250 outside your scroll event like on below:

var current_pos = 1250; //paste it here

$(window).scroll(function() {
    var offset = $(window).scrollTop();
    if(offset > current_pos) {
        current_pos += 1250;
        //do some function
   }
});

Upvotes: 2

Related Questions