I did this a while ago, here is the code I created for this: View JSFiddle .
(You may have to change your layout a bit, I'm not sure how well this will work with the table'd layout you have, I would suggest using divs and putting them in your content layout.), Alternatively, you can use code / logic below and roll your own with your own layout.
Basically,
- Get our items
- Get sidebar position on download page
- Get #content.outerHeight()
Once we have these vars, in the window scroll test, to find out if we were <= (less than or equal to) our original sidebarTop position or to check if we blogHeight , if any of 2 is true, remove the sticky class. elseif our scroll >= our starting position is sidebar , then add the .sticky class (which has position: fixed ).
Check out JSFiddle (click here)
Javascript looks like this:
// Cache our vars for the fixed sidebar on scroll var $sidebar = $('#sidebar-nav'); // Get & Store the original top of our
HTML :
<header>This is the header!</header> <ul id="sidebar-nav" class="nav nav-list"> <li><a href="#">Home</a></li> <li><a href="#">Blog</a></li> </ul> <div id="content">Content in here, scroll down to see the sticky in action!</div> <div class="clear"></div> <div id="footer">This is the #footer</div>
CSS :
#sidebar-nav.sticky {position:fixed;top:5px;} header { border:1px solid #aaa; background-color:yellow; margin-bottom:5px; height:50px; } #sidebar-nav { width:150px; border:1px solid #ddd; margin:0; padding:0; float:left; } #sidebar-nav li { list-style:none; border:1px solid #ddd; margin:10px; padding:2px; } #content { height:2000px; width:500px; padding:10px; border:1px solid #ddd; margin:0 0 10px 5px; float:right; } #footer { height:800px; border:1px solid green; background-color:#ddd; } .clear { clear:both; }
:)
source share