Search code examples
jqueryscrollsidebar

jQuery scroll/follow sidebar (div)


used the jquery technique for a scrolling/following sidebar from Help with Scroll/Follow Sidebar

$(function() {
    var $sidebar   = $(".sidebar"),
        $window    = $(window),
        $footer    = $(".footer"), // use your footer ID here
        offset     = $sidebar.offset(),
        foffset    = $footer.offset(),
        threshold  = foffset.top - $sidebar.height(), // may need to tweak
        topPadding = 15;

    $window.scroll(function() {
        if ($window.scrollTop() > threshold) {
            $sidebar.stop().animate({
                marginTop: threshold
            });
        } else if ($window.scrollTop() > offset.top) {
            $sidebar.stop().animate({
                marginTop: $window.scrollTop() - offset.top + topPadding
            });
        } else {
            $sidebar.stop().animate({
                marginTop: 0
            });
        }
    });
});

the only problem is when the sidebar(.sidebar) reaches footer (.footer) it pushes down the footer nearly about height of the footer.
If the height of footer is 200px, sidebar pushes footer to ~200px(Internet Explorer), ~50px(Firefox, Chrome, Opera) then display footer.
200px of blank space between content and footer is my real problem.
I want the sidebar to stop scrolling exactly where the footer begins.


Solution

  • try

     threshold = foffset.top - $sidebar.height() - offset.top