Jquery window scroll. call just one time

4.4k Views Asked by At

Hi I have one question about jquery window scroll function. I have code somthing like this.

$(window).scroll(function(){
        if($(window).scrollTop() > $(".pages").offset().top) {
            $('.top-slider').slick('slickPause');
        }else {
            $('.top-slider').slick('slickPlay');
        }
    });

Ok every time when you scroll if first is true it call every 1px scrolled window. Is that way to call just one time if true but check on scroll if other is true call that just one time?

Thanks for your answers :)

3

There are 3 best solutions below

0
On BEST ANSWER

Try with a flag, something like this:

var paused = false;

$(window).scroll(function(){
    if( $(window).scrollTop() > $(".pages").offset().top ) {
        if( !paused ){
            $('.top-slider').slick('slickPause');
            paused = true;
        }        
    }else {
        if( paused ){
            $('.top-slider').slick('slickPlay');
            paused = false;
        }
    }
});
1
On

Adding a test variable will be a solution here :

var checkDown = true; 
var checkUp   = false;
$(window).scroll(function(){
    if($(window).scrollTop() > $(".pages").offset().top && checkDown ) {
        $('.top-slider').slick('slickPause');
        checkDown = false;
        checkUp   = true;
    }else if(checkUp) {
        $('.top-slider').slick('slickPlay');
        checkDown = true;
        checkUp   = false;
    }
});
2
On

I tell you another solution, is a debouncer. Debounce functions make scroll and resize events more efficient, because stop the event firing till the end of the first fired event.

You can view a debounce function with underscore.js library.

http://underscorejs.org/#debounce

The use is simple:

var debounced = _.debounce(myFunction, 1000);
$(window).scroll(debounced);