add class when scroll nav bar
Front End Development

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

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

Luke Dowding
I’m a UX/UI Designer & Web Developer from the UK. I’m Vegan, love Cycling, Running, Gaming and F1. Aka: Roamy
Tags : , , , , , ,
March 17, 2017