Sticky Sidebar in 10 Minutes
July 24, 2013 7:33 am Leave your thoughtsThere 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<div class="bodyContainer"> <div id="theHeader"> <h1>Fiddling with sticky top side bar</h1> </div> <div id="theContent"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nam cursus. Morbi ut mi. Nullam enim leo, egestas id, condimentum at, laoreet mattis, massa. Sed eleifend nonummy diam. Praesent mauris ante, elementum et, bibendum at, posuere sit amet, nibh. Duis tincidunt lectus quis dui viverra vestibulum. <br /><br /> Suspendisse vulputate aliquam dui. Nulla elementum dui ut augue. Aliquam vehicula mi at mauris. Maecenas placerat, nisl at consequat rhoncus, sem nunc gravida justo, quis eleifend arcu velit quis lacus. Morbi magna magna, tincidunt a, mattis non, imperdiet vitae, tellus. Sed odio est, auctor ac, sollicitudin in, consequat vitae, orci. Fusce id felis. Vivamus sollicitudin metus eget eros. <br /><br /> Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In posuere felis nec tortor. Pellentesque faucibus. Ut accumsan ultricies elit. Maecenas at justo id velit placerat molestie. Donec dictum lectus non odio. Cras a ante vitae enim iaculis aliquam <br /><br /> Mauris nunc quam, venenatis nec, euismod sit amet, egestas placerat, est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Cras id elit. Integer quis urna. Ut ante enim, dapibus malesuada, fringilla eu, condimentum quis, tellus. Aenean porttitor eros vel dolor. Donec convallis pede venenatis nibh. Duis quam. Nam eget lacus. Aliquam erat volutpat. Quisque dignissim congue leo. <br /><br /> Mauris vel lacus vitae felis vestibulum volutpat. Etiam est nunc, venenatis in, tristique eu, imperdiet ac, nisl. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. <br /><br /> In iaculis facilisis massa. Etiam eu urna. Sed porta. Suspendisse quam leo, molestie sed, luctus quis, feugiat in, pede. Fusce tellus. Sed metus augue, convallis et, vehicula ut, pulvinar eu, ante. Integer orci tellus, tristique v <br /><br /> But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. <br /><br /> No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. <br /><br /> Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. <br /><br /> To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure? <br /><br /> On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. <br /><br />These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. <br /><br /> But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. <br /><br /> The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains. But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because </div> <div id="theNavigationWrapper"> <div id="theNavigation"> <ul> <li>Stuff 1</li> <li>Stuff 2</li> <li>Stuff 3</li> </ul> </div> </div> <div style="clear:both"></div> </div> |
The CSS
Below is the simple stylesheet for our simplistic layout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
body { font-family: helvetica, sans-serif; padding: 0px; margin: 0px; } div { border-radius: 3px; } #btnCalc { position: fixed; top: 0px; left: 0px; } #theHeader { background-color: #b10339; text-align: center; color: #fff; padding: 8px; display: block; margin-bottom: 10px; } .bodyContainer { width: 670px; margin: 0px auto; box-shadow: 0 0 250px #834; } #theContent { display: block; float: left; width: 430px; background-color: #ffe3e3; padding: 8px; } #theNavigationWrapper { display: block; float: right; } #theNavigation { display: block; width: 200px; background-color: #b10339; padding: 8px; } #theNavigation.sticky { position: fixed; top: 0px; } #theNavigation ul { list-style-type: none; margin: 0px auto; display: block; padding: 0px; text-align: center; } #theNavigation li { background-color: #ffe3e3; border-radius: 3px; margin: 3px; } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
$(document).ready(function() { $('#theNavigation').waypoint(function(direction) { if (direction == "down") { $(this).addClass("sticky"); } else { $(this).removeClass("sticky"); } }, {offset: 0} ); }); |
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.
Demo
Tags: javascript, jQuery, waypointjsCategorised in: Javascript, jQuery, Web Design