Irina
Irina

Reputation: 69

Sticky header animation working when scrolling down but not when scrolling up

code sandbox: https://codesandbox.io/s/nostalgic-morning-3f09m?file=/src/App.tsx

So, I have a sticky header which should appear once the user has scrolled a X amount of pixels (420px in this example). Once it hits 420px, it shows an animation sliding the header down. When I scroll the screen back up, however, the sticky header just "disappears" in a very cold way. The idea is that it would also "slide" up and disappear in a reverse way as it appeared. An example of what I want to achieve -> https://www.pretto.fr/ I want exactly this, for the header to slide when it comes down but when I scroll back up, for it scroll up disappearing.

The difference is that in this website the sticky header and the "main" header are two different components it seems. On my website, they are just one, and I'm just using props for it to go from position: relative; to position: sticky;

My header:

function Header(props: HeaderProps): React.ReactElement {
  const [sticky, setSticky] = useState(false)

  useEffect(() => {
    document.addEventListener('scroll', trackScroll)

    return () => {
      document.removeEventListener('scroll', trackScroll)
    }
  }, [])

  const trackScroll = () => {
    if (typeof window == 'undefined') {
      return
    } else {
      setSticky(window.scrollY >= 420)
    }
  }

  return (
    <Container id="container" sticky={sticky} className={`${sticky ? 'sticky' : ''}`}>
    ...

And my styled-components styles...

const smoothScroll = keyframes`
  0% { transform: translateY(-100%); }
  100% { transform: translateY(0px); }
`

const Container = styled.div<{ sticky?: boolean }>`
  display: flex;
  justify-content: space-between;
  margin: auto;
  padding: 0 6rem;
  width: 100%;
  position: ${props => (props.sticky ? 'sticky' : 'relative')};
  top: 0px;
  height: 97px;
  align-items: center;
  z-index: 3;
  background: ${props => (props.sticky ? 'white' : 'inherit')};

  &.sticky {
    animation: ${smoothScroll} 500ms;
  }
`

So the nice "sliding down" animation works once I scroll down to 420px. But as soon as I scroll back up it just disappears instead of "sliding up". Any ideas on how to achieve this?

Upvotes: 1

Views: 1721

Answers (1)

Simon Dubek
Simon Dubek

Reputation: 240

I added another sticky navigation that uses an inline style to change the transform and a transition to animate it. You could also achieve this by changing the position and some other styles on the original navigation and thereby get rid off the second sticky navigation but I think this is much more clear.

Would this work for you: https://codesandbox.io/s/zen-raman-qtitt

Upvotes: 1

Related Questions