I have an element with position:fixed (a sidebar / side content area). I want to make 2 separate headers (one for scrolled to top, and one for scrolls down).
I need to add a body class (.scrolled-down or something) when the user scrolls down the page, and then remove it when they are scrolled to the top. That’s because the amount of padding for the sidebar is dependent upon the height of the header.
For example:
.scrolled-up #sidecontent {padding-top: 60px) ///to accommodate a bigger header
I know you have posted a straight-forward useable answer, but I just wanted to toy around with some optimizing and throttling — admittedly a more convoluted solution.
Again a link to the Debounce and Throttling article. Note lodash’s _.debounce and _.throttle are recommended in the article, which makes sense
Okay now that we’re talking about throttling… :-) FWIW I think the best way to avoid layout thrashing is to just schedule the callback execution to the next animation frame – i.e.:
This way you can be sure not to “interrupt” the browser during its regular painting business; more extended delays should only be necessary for really expensive calculations.
The only issue I see is that these seem to add the .scrolled-down class after any amount of scrolling.
My “scrolled-up” header is 190px tall, and my scrolled down header is only about 50px tall.
So, if the user scrolls down < 140px, the .scrolled-down will be added, but the margins (I am modifying with the .scrolled-up/down class) won’t match up…
In essence, I need more grainular control (by pixel height) over when to add the selectors.