Search code examples
jquerycsssidebar

Help with Scroll/Follow Sidebar


used the jquery technique to have a scrolling/following sidebar from css-tricks.com, here is the code if you dont know what im talking about:

$(function() {

        var $sidebar   = $("#scroll-menu"),
            $window    = $(window),
            offset     = $sidebar.offset(),
            topPadding = 15;

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

    });

also here is the link http://css-tricks.com/scrollfollow-sidebar/

The only problem that i have with this is that it has an container but when you scroll far enough into footer the sidebar scrolls out of container. Is there a way i can constrain how far it scrolls down?

Here is an image of what is happening: http://tinypic.com/r/2mcj2mv/7

Thanks in advance


Solution

  • You just need to add an extra conditional statement that does nothing if $(window).scrollTop() is greater than a certain threshold. The problem lies in setting that threshold as I assume you want it to work on pages of varying heights. Fortunately we can use the offset of the footer and the height of the sidebar to determine this threshold. The following might need some tweaking for your particular situation, but basically:

    $(function() {
    
        var $sidebar   = $("#scroll-menu"),
            $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
                });
            }
        });
    
    });