Jquery Sticky Sidebar
Jul 25, 2011 | In jQuery, Tutorials |Today, I will be showing you guys how to make a simple jquery sticky sidebar script.
We’ll start off with some basic html markup:
<div id="container"> <div class="sticky"> </div> <div id="text"> </div> </div>
We have a main container that holds everything, a sticky sidebar div, and a text div. Now, we’ll position these elements, and style the sidebar into a stylish square.
.sticky { margin-top: 300px; float: left; background: #6c6c6c; height: 144px; width: 144px; } .sticky:hover { background: #4c4c4c; } #text { width: 500px; float: right; } #container { width: 744px; }
As you can see, we have a container that holds two things: A div with some example text, and the sticky sidebar.
We also styled the sidebar; we gave it a nice grey background. Now, the reason our text div is floated to the right is because when we scroll down far enough, the sticky div will become “position: fixed”, which could potentially disrupt the layout.
In the third and final stage of this tutorial, we will add the code that will make this work. I’ll show you all the code, and then walk you through it, step by step.
var offset = $('#sticky').offset(); var topOffset = offset.top; var leftOffset = offset.left; var marginTop = $('#sticky').css("marginTop"); var marginLeft = $('#sticky').css("marginLeft"); $(window).scroll(function() { var scrollTop = $(window).scrollTop(); if (scrollTop >= topOffset){ obj.css({ marginTop: 0, marginLeft: leftOffset, position: 'fixed', }); } if (scrollTop < topOffset){ obj.css({ marginTop: marginTop, marginLeft: marginLeft, position: 'relative', }); } });
First, we declare some variables. These variables contain our sticky element’s offset from the top and left of the page, as well as its margins from the top and the left. Then, we have a window scroll function. This means, “when the user scrolls, do this”. Next, we declare a variable that contains how far the user has scrolled from the top. Hence, “scrollTop”. Our last chunk of code contains the logic of the whole thing. Read carefully: If, when we scroll the page, we scrolled to the position of $(‘#sticky’) or farther, then set some css for $(‘#sticky’). Specifically, we tell it to be “position: fixed”, which also makes it absolute. Since its absolute now, we have to set some margins relative to the document. We give a margin-left equivalent to its left offset before. We also tell it to have “margin-top: 0″. Change this to whatever you want, it doesn’t matter.
The second “if” statement is also important. Imagine that we scrolled down, made the $(‘#sticky’) element fixed, and then scrolled back up. We would have to de-sticky the element, and return it to its former position. So, we tell it to have a relative position, and give it back its old margins. Ta-da! A nice, reusable, sticky script. So reusable as a matter of fact, that I made it into a super simple plugin called “jsticky”. Go ahead, click on that link below.
LINK: Jsticky.