Hide horizonal menu on scroll

I am trying to create a horizontal top menu that disappears as the user scrolls down the page. I have got part-way there - it does disappear, but before it disappears it flashes on and off. I’m jiggered if I can see why.

Here’s my codepen:

When I’ve got that working, I would like the menu to scroll out of view rather than just vanish. I realise that that won’t be done using the display attribute. :upside_down_face:

Hey Gandalf - it’s flickering because as you start scrolling, and you get 50px more down the page, you hide the header, which then removes the header height from the page scroll position so you get the jittering. So you might be scrolling from 0-100px and at 50px, the header hides and you get back below 50px so the header goes through a show/hide spasm.

If we just go ahead and make the header slide out of view, thus never removing its height from the page flow, we remove the jitters:

3 Likes

Hey Ryan. Many thanks for both the explanation and the solution.

2 Likes

I wanted to get the menu to come back if the user starts scrolling up again. I think to check if the user is scrolling up I check the current Y position with the last but something’s not right either with my thinking or my code (or both!)

I’ve modified my codepen:

A bit rusty Gandalf, but if you just amend @RyanReese 's script to translateY doesn’t that work?

window.onscroll = function() {
document.querySelector("header").style.transform = (window.scrollY > 50)
    ? "translateY(-100%)"
    : "translateY(0%)";
};

That moves the menu up rather than to the right, @rpg_digital but getting the menu to reappear if the user scrolls up is defeating me.

@Gandalf ah ok, as I say a bit rusty.

1 Like

I have an example here that may help.

It uses jquery but you should be able to follow the logic.

Actually I think this one is easier to follow.

2 Likes

Thanks, Paul. I shall play. Should keep me out of trouble for a bit…

2 Likes

Yay! I managed to fix it with help from your codepens @PaulOB and a good night’s sleep :grin:

(I’ve updated the pen in case it helps anyone else.)

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.