Search code examples
javascriptjquerycallwindow-scroll

Jquery window scroll. call just one time


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 :)


Solution

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