Sticky Sidebar in 10 Minutes

July 24, 2013 7:33 am Leave your thoughts

There had been a couple occasions where I had to create a sidebar on a website that will stay visible no matter how much the user scrolled. This is pretty easy of course if you just want to stick the sidebar to the absolute top using fixed positioning, but of course normally a website would have either a header or horizontal navigation at the top of the site or even both.

The obvious solution that comes to mind is to calculate the top offset position of the sidebar using javascript and detect when the top of the sidebar hits the top of the current browser window. We can of course write a jQuery based script to do so, however you will have to deal with many edge cases such as detecting when the top of the side bar appears on the screen again or trigger the stickyness only when the sidebar is at certain points and many more.

A great library called Waypoint already deals with those cases and I always think that when a good and proper solution for your project exists out there, then you shouldn’t reinvent the wheels. Some people may have different opinion, however for commercial projects or time sensitive projects it would be more important to deliver a robust solution than to re-invent the same thing with potential issues. Unless of course you can come up with something much better.

Anyway, here is the way to come up with the solution in 10 mins. In this example, I have a simple 2 columns design with a header. The objective is to float the right side bar when the user scrolls down the page in order to keep the sidebar in view all the time.

The Sample HTML


Below is the simple stylesheet for our simplistic layout.

The most important point on the above CSS is the style #theNavigation.sticky. This is the CSS class the sticks the side bar to the top whenever the “sticky” class is attached to theNavigation.

The Javascript

Firstly don’t forget to download and include jQuery and waypoint library. jQuery can be downloaded here, while Waypoint can be downloaded here.

After including those two libraries, the JavaScript that we have to write is extremely simple.

The above script is simply attaching the waypoint handler to the navigation element. The parameter “direction” is actually an in-built parameter from Waypoint js. Simply put if the user scrolls down, add the sticky class to the side bar navigation element, while scrolling up will remove the sticky class as the side bar as the top of the side bar moves past the user’s browser window top.

So there you go, sticky sidebar in 10 minutes or less. See below for the demonstration.


Tags: , ,

Categorised in: , ,