Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle class during scroll function

If it possible to somehow write a snippet that during the scroll function on the window the body is appended with a class?

$(window).scroll(function() {
    $('body').toggleClass('scrolling');
 });

If the user is scrolling then the body has a class of 'scrolling'. If the scroll is not currently happening, the body has no class.

The scroll function seems to rapidly fire with the function above.


1 Answers

There isn't a "scroll start" and "scroll end" pair like "mouse down" and "mouse up": the "scroll" event is more of a "scroll just occurred". You can set a timeout to clear your "scrolling" class if no scroll has happened for n milliseconds:

var scrollTimerId;

$(window).scroll(function() {
    if (!scrollTimerId)
       $('body').addClass('scrolling');

    clearTimeout(scrollTimerId);
    scrollTimerId = setTimeout(function(){
        $('body').removeClass('scrolling');
           scrollTimerId = undefined;
    },150);
});

Demo: http://jsfiddle.net/8CaRE/2/

(Vary the delay until you find something you're happy with - for me 150ms seems a reasonable setting in Chrome.)

like image 71
nnnnnn Avatar answered May 25 '26 18:05

nnnnnn