DEV Community

Cover image for Show and hide a header based on scroll direction

Show and hide a header based on scroll direction

Chris Bongers on January 09, 2022

This article actually has a funny origin as it was requested by my good friend Fredrik asked me to help with a specific menu. He initially reached...
Collapse
 
lexlohr profile image
Alex Lohr

One tiny optimization: classList.toggle has a little known optional second boolean argument which overrides the class being (in)active. So

if (windowY < lastScroll) {
  header.classList.add('scroll-up');
} else {
  header.classList.remove('scroll-up');
}
Enter fullscreen mode Exit fullscreen mode

becomes

header.classList.toggle('scroll-up', windowY < lastScroll);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dailydevtips1 profile image
Chris Bongers

Oh nice actually never used that one, time to look into that
Thanks Alex 💖

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

Just a thing, I'm on my smartphone (Google Pixel 5 just for screen reference) and it does not work on the first "half" which is weird specialy on mobile which is the desirable target place for this feature.

That being said I'll totally change the condition for that. If you think on a landscape it will work -probably- but on portrait, Y is always greater than X axis.

Collapse
 
dailydevtips1 profile image
Chris Bongers

Hey Joel,

It should not work on the first section on all devices, is that what you mean?
The rest of the condition should fire, so from the second onwards you should see the header when scrolling up.

But i'll double check my mobile implementation.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

I mean that this feature is specially useful in mobile but you decided to make it to not work in the first section, which makes it unusable for some piece of screen, I've just wondering why

Thread Thread
 
dailydevtips1 profile image
Chris Bongers

Ah right!
It's mainly because the page the idea comes from uses that approach so wanted to make sure to include that as well.