Fixed sidebar on scoll down page
Have a floating sidebar which fixes into position when the user scrolls past a set height and reverts back to floating when they scroll back above that height.
Also it will only instantiate if the browser window is over a specified height so for smaller pages it won't ever become fixed.
HTML
<div id="header">
<h1>Header</h1>
</div>
<div id="main">
<h1>Main</h1>
</div>
<div id="sidebar">
<h1>Sidebar</h1>
</div>
CSS
#header {
width: 450px;
height: 150px;
border: 1px solid #000;
margin-bottom: 20px;
}
#main {
float: left;
height: 2000px;
width: 290px;
margin-right: 10px;
border: 1px solid #000;
}
#sidebar {
float: left;
width: 150px;
height: 300px;
border: 1px solid #000;
}
.sidebarFixed {
position: fixed !important;
top: 0 !important;
left: 302px !important;
}
JavaScript
$(document).ready(function() {
// IE 6 doesn't implement position fixed nicely...
if (window.XMLHttpRequest) {
window.onscroll = function() {
if ($('body').scrollTop() > 170 || $('html').scrollTop() > 170) {
if ($(window).height() > 20) {
$('#sidebar').addClass('sidebarFixed');
}
}else {
$('#sidebar').removeClass('sidebarFixed');
}
if ($('body').scrollBottom() > 170 || $('html').scrollBottom() > 170) {
if ($(window).height() > 20) {
$('#sidebar').addClass('sidebarFixed');
}
}
};
}
});