stick nav bar javascript
Front End Development

Simple Sticky Nav made with Javascript & jQuery

This stick nav bar just uses a bit of Javascript with jQuery and very little code, so should drop into any project youre working on. A sticky nav bar or just a stick div can be used for many things, this will work for any div that you want to stick to the top of the window as the user scrolls. Just bare in mind that we use Position: fixed; so it will be above everything else on the page. Make sure to text this on all devices sizes to ensure a good user experience.

So how does it work?

 

HTML Structure

See the Pen Sticky Div, sticks to the top by Luke Dowding (@LukeD1uk) on CodePen.0

Pretty simple, I am using a container here to simply simulate a page. I always make sure to apply my CSS to classes not id’s even if that means I have a class and an id that’s how it should be done. Its a best practice to never apply CSS to id’s.

CSS

See the Pen Sticky Div, sticks to the top by Luke Dowding (@LukeD1uk) on CodePen.0

Most of the CSS is really just for the mockup, I had added a bunch of padding at the bottom of the container so you can scroll and test it.

Javascript/jQuery

See the Pen Sticky Div, sticks to the top by Luke Dowding (@LukeD1uk) on CodePen.0

So as you can see the Javascript is doing all the work here, if you take a look at the IF statement, IF the div hits the top it applies some CSS to keep it fixed. If the div is not at the top so ELSE it will apply the default positioning CSS of the div.

The Result

See the Pen Sticky Div, sticks to the top by Luke Dowding (@LukeD1uk) on CodePen.0

As you can see when you scroll down, once the div hits the top of the window, it becomes fixed. as you scroll back up the div will go back to its previous Static positioning.

 

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
March 14, 2017