In this Javascript Tutorial, we will be using the jQuery library to create an Animated Fixed Nav Bar that has being commonly used in today’s web sites. The idea is that when you scroll past a certain point, the header will stay fixed to the top of the page and shrink down to a smaller size but still give the user the ability to navigate to another page at will. This will require us to add or remove a css class at a certain scroll point. Our example will look similar to the image below.

animated fixed scroll bar

Setup

First we must markup our HTML and CSS. We will also make another class called “small-nav” that we will add and remove with jQuery. It is important to set up our CSS before hand so when the class is added, the DOM knows what to reference. Let’s take a look.

As you can see, we’ve included a classes “nav.small-nav”. This class will be appended to the nav using jQuery and overwrite the height and line-height properties inside the nav tag. It is also important to note that you must include the jQuery library in the header in order for this to work. If you preview the document in your browser, you will see the beginnings of our project.

The Javascript

Now it’s time to add the code that will make it all happen. As stated before, it is as simple as adding and removing a css class. But when exactly do we add the class? We must give the computer some logic to go by to determine when it is appropriate to add the “small-nav” css class. Here is what we came up with.

In order for us to understand what is happening, let’s break it down line by line and see what we can learn from this code.

  1. First we start our function
  2. We create a variable that stores the pixel value the scroll bar must reach
  3. We call the scroll method to the window and tie a function with an if/else statement (this will be the decision making part of our code)
  4. Decision 1: if the value of our window scroll is greate than smallHeader (150px), add the “small-nav” class to the “nav” element.
  5. Decision 2: if the window scroll is not greater or equal to 150px, than remove the “small-nav” class from the “nav” element.
  6. the last function is a cross browser support that states to use “return window.pageYOffest” OR “document.documentElement.scrollTop;

Save your work and preview it in the browser and you will see your header nav working and fully functional now.

Conclusion

There are many plugins that will give you the fixed animated navigation bar. But as you can see, with a few lines of jQuery, you can have a much more efficient and lightweight solution that you can control. The combination of jQuery and CSS is a powerful front-end tool that can give you great UI and UX results.