Fixed sidebar on scoll down page
Fixed sidebar on scoll down page
by Andrew Pougher
HTML
<div id="header">
<h1>Header</h1>
</div>
<div id="main">
<h1>Main</h1>
</div>
<div id="sidebar">
<h1>Sidebar</h1>
</div>
CSS
body{background:#222222;padding:40px}
#header {
width: 450px;
height: 150px;
border: 1px solid #000;
margin-bottom: 20px;
background:#ffffff
}
#main {
float: left;
height: 2000px;
width: 290px;
margin-right: 10px;
border: 1px solid #000;
background:#ffffff
}
#sidebar {
float: left;
width: 150px;
height: 300px;
border: 1px solid #000;
background:#ffffff;
}
.sidebarFixed {
background:#eeefff;
margin-left:40px;
margin-top:20px;
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');
}
};
}
});