I'm working on a (sticky) scrolling sidebar. The problem is that most sticky sidebars don't take into consideration that the sidebar can be taller then the viewport (e.g. if many items are added to the basket(sidebar)). Which is what I'm trying to solve. These are the requirements:
If the height of the sidebar is taller then the viewport, it should scroll through the content and the bottom of the div should stick to the bottom of the viewport when scrolling further down.
If the height of the sidebar is taller then the viewport, the divs underneath should only be shown when you are at the bottom of the page.
When user scrolls back up, the sidebar scrolls back to the top and sticks back onto the top of the viewport.
If the height of the sidebar is less then the viewport, it should be sticky from the top on when scrolling down.
So all in all quite some functionality and not that simple (I think). The closest I've seen to what I'm trying to achieve is this example: http://demo.techbrij.com/730/fix-sidebar-scrolling-jquery.php but the way the code is written doesn't fit into mine.
So far, this is what I've made: DEMO
And the jQuery code I used:
jQuery(document).ready(function($) {
var $sidebar = $('.sidebar'),
$content = $('.content');
if ($sidebar.length > 0 && $content.length > 0) {
var $window = $(window),
offset = $sidebar.offset(),
timer;
$window.scroll(function() {
clearTimeout(timer);
timer = setTimeout(function() {
if ($content.height() > $sidebar.height()) {
var new_margin = $window.scrollTop() - offset.top;
if ($window.scrollTop() > offset.top && ($sidebar.height()+new_margin) <= $content.height()) {
// Following the scroll...
$sidebar.stop().animate({ marginTop: new_margin });
} else if (($sidebar.height()+new_margin) > $content.height()) {
// Reached the bottom...
$sidebar.stop().animate({ marginTop: $content.height()-$sidebar.height() });
} else if ($window.scrollTop() <= offset.top) {
// Initial position...
$sidebar.stop().animate({ marginTop: 0 });
}
}
}, 100);
});
}
});