The Problem
So you have a standard sidebar which sits next to your main content, this is good, but if your content is really long the sidebar will disappear as the user scrolls down the page. To preserve the style of your website but ensure your sidebar is always visible you could implement a JavaScript and CSS solution to providing a fixed sidebar when the user scrolls past a certain height.
The Demo
This fixed position sidebar solution should work in all browsers above IE6!
Now you have saw it working I will show you the code that makes it work.
The code
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;
}
JQuery
$(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 you find this useful or have any suggestions then please comment below.






Pingback: webdeveloper