Aram Mkrtchyan
Aram Mkrtchyan

Reputation: 2700

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

Upvotes: 2

Views: 4502

Answers (3)

Marcos Pérez Gude
Marcos Pérez Gude

Reputation: 22158

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

Upvotes: 1

MazzCris
MazzCris

Reputation: 1840

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

Upvotes: 8

Elheni Mokhles
Elheni Mokhles

Reputation: 4001

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

Upvotes: 2

Related Questions