DEV Community

Abhii
Abhii

Posted on • Edited on

Reveal navbar on scroll

Intro and Motivation

DesignCourse's Gary Simon just released a tutorial on the topic that sounds like the title of this blog (I'm not sure if my writing is eligible to be called as a blog 😁)

After I watched that, I thought of recreating it and here I'm showing it to you all.

Let's Start

I'm sure you can write some markup and a lots of the lorem text. So we'll jump right to my javascript logic.

The pre-requisites

  • window.pageYOffset : It basically returns the position of scrollbar. Check out More on pageYOffset
  • Basic JavaScript
  • Basic Logical Resoning
  • Some time

The Logic

When the user scroll's down the navbar must hide itself and when the user starts to scroll up it must reveal itself back.

So let us have some variables,

  1. lastScroll - Stores the just previous scroll position
  2. currentScroll - Stores the currenrt scroll position

If differnce between currentScroll and lastScroll is positive, it means that user has -- SCROLLED DOWN -- and therefore we will hide the navbar.

Similarly, If differnce between currentScroll and lastScroll is negative, it means that user has -- SCROLLED UP -- and therefore we will reveal the navbar

We will also need some css classes to help us perform the magic,

  1. .scroll-up - what happens after user scrolls up
  2. .scroll-down - what happens after user scrolls down

.scroll-up

header.scroll-up{
    transform: translateY(0);
}
Enter fullscreen mode Exit fullscreen mode

.scroll-down

header.scroll-down{
    transform: translateY(-100%);
}
Enter fullscreen mode Exit fullscreen mode

The Code

You can also find the code on GitHub

GitHub logo amdhanwate / reveal-unreveal-on-scroll

Reveal and unreveal the navbar depending upon user's scroll behavior

After words

Do tell me your thoughts on this and I welcome all type of criticism (I don't know the spelling) which would help me become a better developer after all.

Also, a BIG thanks to our developer community for always helping and encouraging everyone around.

I hope you wait for my next article..

Top comments (3)

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
abhilearnstocode profile image
Abhii

Thanks and sure I'll try to recreate it.

Collapse
 
abhilearnstocode profile image
Abhii

What do you want me to do?