Ryan
Ryan

Reputation: 105

Make Div appear only when the page is scrolling

I know this question is a bit vague, but I am more wondering if what I am asking about is even possible. I know it is fairly easy to trigger an event when a user hits a specific point on a web page, but I want to know if it is possible to only show a div or maybe only apply a class when the page is actively scrolling then unapply it all once scrolling stops.

An example would be to have a fixed div at the top of a way page this is blue but only while no scrolling occurs. While scrolling is occurring that div would turn red then once the user stopped scrolling again it would go back to blue. I can see how to use an onScroll to change the div once a scroll starts, but I'm not too sure how to revert back to that initial state/class/whatever. Thanks.

Upvotes: 2

Views: 77

Answers (1)

Kai Qing
Kai Qing

Reputation: 18843

This wouldn't be specific to react, but you can have your scroll event set the scroll state on an element, then override a time out call to unset that. Basic jquery example might be something like this:

var killscroll = null;

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

    clearTimeout(killscroll);

    killscroll = setTimeout(function(){
        $('.element').removeClass('scrolling');
    }, 100);
});

Since scroll fires a lot as you scroll, this would be redefining the timeout until scroll stops firing, then 100 ms later your class would be removed. Adjust the timing as needed.

Used jquery for ease of readability. If you need a raw js example I can update.

Here's a codepen

I assume react has something equivalent to gatsby's wrapRootComponent so you would drop your final code where you would set event listeners. Perhaps componentDidMount

Upvotes: 2

Related Questions