I wish to scroll down, and view #div1... also see #div2... When #div2 disappears from sight, I want #div1 to slide down and stay fixed at the top of the window. If I reach the footer div, I no longer want #div1 to remain sticky.
If it's possible for this effect to work in reverse (scrolling up the page), that would be ideal. There are no set heights involved. Is there a way to achieve this with jQuery?
Click here for a live example on jsFiddle
$(document).scroll(function() {
var y = $(this).scrollTop();
var div3 = $('#div3').offset().top;
if (y > div3) {
$('#div1').addClass('sticky');
} else {
$('#div1').removeClass('sticky');
}
});