Scrolling sidebar
by mylastof
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<div id="header"> header </div>
<div class="row" id="contentHolder">
<div class="col-sm-3 ">
<div class="sidebar">
sidebar
</div>
</div>
<div class="col-sm-9">
<div class="content">
content
</div>
</div>
</div>
<div id="footer"> footer </div>
</div>
CSS
#wrapper {
margin: 0 auto;
width: 100%;
}
#contentHolder{
position:relative;
}
#header, #footer {
background: #CCFFFF;
color: #000000;
height: 80px;
width: 100%;
clear:both;
font-size:3em;
text-align:center;
padding-top:20px;
}
.sidebar {
background: teal;
position: relative;
height: 1000px;
}
.leftsidebarfixed {
position: fixed;
top: 0;
}
.content {
background: orange;
position: relative;
height: 10000px;
}
JavaScript
$(function () {
var msie6 = $.browser == 'msie' && $.browser.version < 7;
if (!msie6 && $('.sidebar').offset()!=null) {
var top = $('.sidebar').offset().top - parseFloat($('.sidebar').css('margin-top').replace(/auto/, 0));
var height = $('.sidebar').height();
var winHeight = $(window).height();
var footerTop = $('#footer').offset().top - parseFloat($('#footer').css('margin-top').replace(/auto/, 0));
var gap = 7;
$(window).scroll(function (event) {
// what the y position of the scroll is
var y = $(this).scrollTop();
// whether that's below the form
if (y+winHeight >= top+ height+gap && y+winHeight<=footerTop) {
// if so, ad the fixed class
$('.sidebar').addClass('leftsidebarfixed').css('top',winHeight-height-gap +'px');
}
else if (y+winHeight>footerTop) {
// if so, ad the fixed class
$('.sidebar').addClass('leftsidebarfixed').css('top',footerTop-height-y-gap+'px');
}
else
{
// otherwise remove it
$('.sidebar').removeClass('leftsidebarfixed').css('top','0px');
}
});
}
});