jQuery Scroll follow

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Mads Klitgaard
    New Member
    • Oct 2010
    • 1

    jQuery Scroll follow

    I have a sort of sidebar on my website, which has to scroll down together with the user so that it is always in the view.

    The code I'm using now is actually working fine however there is one problem. On smaller screens the sidebar scrolls before your at the sidebar thus making it impossible to see it all even if you scroll.

    So what I want is the sidebar to scroll with the bottom instead of it being pushed down with the top so that when you reach the end of the sidebar it starts to scroll.

    This is the code that I'm currently using.

    Code:
    <script type="text/javascript">
        var documentHeight = 0;
        var topPadding = 10;
        $(function() {
            var offset = $("#mainright").offset();
            documentHeight = $(document).height();
            $(window).scroll(function() {
                var sideBarHeight = $("#mainright").height();
                if ($(window).scrollTop() > offset.top) {
                    var newPosition = ($(window).scrollTop() - offset.top) + topPadding;
                    var maxPosition = documentHeight - (sideBarHeight);
                    if (newPosition > maxPosition) {
                        newPosition = maxPosition;
                    }
                    $("#mainright").stop().animate({
                        marginTop: newPosition
                    });
                } else {
                    $("#mainright").stop().animate({
                        marginTop: 0
                    });
                };
            });
        });
    </script>
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    Can you not use "position:fixed " instead?

    Comment

    Working...