user120944
user120944

Reputation:

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.

Upvotes: 3

Views: 2035

Answers (2)

nnnnnn
nnnnnn

Reputation: 150080

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

Upvotes: 1

Blazemonger
Blazemonger

Reputation: 92953

Probably isn't very healthy performance-wise, but you could add a setInterval to remove the class every few milliseconds combined with your scroll handler to add it when scrolling.

$(window).on('scroll', function() {
    $('body').addClass('scrolling');
});

setInterval(function() {
    $('body').removeClass('scrolling');
}, 100);​

http://jsfiddle.net/pYVL8/

Or, slightly optimized:

setInterval(function() {
    document.getElementsByTagName('body')[0].className = '';
}, 100);​

http://jsfiddle.net/pYVL8/1/

Upvotes: 0

Related Questions