I have a similar setup. I needed a "sticky" div that started at the top of the content section (300px below the top of the page, due to the header), was fixed while I scrolled down, but stopped when I got to a certain point (the footer). With pure CSS, the sticky div was going behind my footer after I got to the bottom. Your code got me going in the right direction, but here's the changes I made for my use case:
$(document).ready(function () {
var length = $("#left").height() - $("#sidebar").height();
$(window).scroll(function () {
var scroll = $(this).scrollTop();
var height = $('#sidebar').height() + 'px';
if(scroll <= 0) {
$("#sidebar").css({
'position': 'absolute',
'top': '0'
});
} else if(scroll >= length) {
$("#sidebar").css({
'position': 'absolute',
'bottom': '0',
'top': 'auto'
});
} else {
$("#sidebar").css({
'position': 'fixed',
'top': '300px'
});
}
});
});