简体   繁体   中英

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.

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
   }
});

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
   }
});

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM