add class when scroll nav bar

Change Nav bar (menu) and add a css class when scroll

Posted by
(Last Updated On: March 14, 2017)

What do you mean a nav bar that changes when you scroll? Well no doubt you’ve seen these on websites, when the nav bar (menu) is transparent over the top of a nice hero image and as soon as you scroll down it changes to a white background so its visible on the rest of the page. This method could be used for anything, from changing the navigation state to revealing a div as the user scrolls down. In the JS you will be able to control the pixel height in which the class is added so there is a lot you could do with this.

So how does it work?

 

HTML Structure

See the Pen Add class on scroll by Luke Dowding (@LukeD1uk) on CodePen.0

Not a lot to say here, nav bar and a footer to simulate a page.

CSS

See the Pen Add class on scroll by Luke Dowding (@LukeD1uk) on CodePen.0

For this effect to work CSS is actually doing the work and we use JS to enable it. I have my nav bar fixed to the top of the page and the style I like. When I scroll down I have the JS setup so it will add the class .scrolled. Using CSS I can style this nav bar pretty much anyway I like and can even implement animations and more.

Javascript/jQuery

See the Pen Add class on scroll by Luke Dowding (@LukeD1uk) on CodePen.0

All we are doing here is adding a class when the windows goes 50 pixels down the page, and removing that class once we go above 50 pixels. You will need to add jQuery to you project for this to work.

The Result

See the Pen Add class on scroll by Luke Dowding (@LukeD1uk) on CodePen.0

As you can see when you scroll downthe div simple changed to the style of my .scrolled class with a simple an effective piece of JS.

I hope this helps with your project, let me know in the comments down below.

Thanks

2 comments

  1. Since a hour I search a Solution to change the CSS-Code when i Scroll down with the entire Screen. My Menubar must be Whithe at the Top from the Site and it must to change the Color when the Visitor scroll the page down.

Leave a Reply

Your email address will not be published. Required fields are marked *