Chris
Chris

Reputation: 2488

Can I declare logic on jQuery for the start and end of a scrolling event?

I would like to setup logic for when the user begins scrolling around the page and after the scrolling is finished, how can I accomplish this?

I want to avoid the below as it means my logic will be fired repeatedly unnecessarily

$(window).scroll(function(){
    console.log("scrolling");
});

Upvotes: 1

Views: 5374

Answers (1)

Yi Jiang
Yi Jiang

Reputation: 50115

You can try defining you're own debounced events. A (very crude) implementation would look something like this:

var t, l = (new Date()).getTime();

$(window).scroll(function(){
    var now = (new Date()).getTime();

    if(now - l > 400){
        $(this).trigger('scrollStart');
        l = now;
    }

    clearTimeout(t);
    t = setTimeout(function(){
        $(window).trigger('scrollEnd');
    }, 300);
});

See: http://www.jsfiddle.net/yijiang/fGmbe/ for a live demo

Upvotes: 9

Related Questions