Search code examples
javascriptjquerysticky

Sticky sidebar scrolling lag and infinite scroll


I have a sidebar that scrolls down with the page. However, the sidebar seems to lag behind the scrolling of the page, ex. scroll down and sidebar shows up a few seconds later. Also, the sidebar will keep going down, making the page longer, and causing the footer to become inaccessible. What do I need to do to make the sidebar move with the scroll and for the sidebar to stop moving at the footer? Here is my jQuery code:

            $(function() {

                var $sidebar   = $("aside"), 
                    $window    = $(window),
                    offset     = $sidebar.offset(),
                    topPadding = 50;

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

            });

An example can be seen at http://meddiary.com/plans-pricing/. Fixing the code is welcomed but just pointing me in the right direction is the best.


Solution

  • This is how I fixed my issue:

                if ($(window).width() > 767) {
    
                    var $sidebar   = $("aside"), 
                        $window    = $(window),
                        offset     = $sidebar.offset(),
                        topPadding = 50;
    
                    $window.scroll(function() {
                        if($window.scrollTop() > $('h3').offset().top) {
                            $sidebar.stop().css('marginTop', '680px');              
                        } else if ($window.scrollTop() > offset.top) {
                            $sidebar.stop().animate({
                                marginTop: $window.scrollTop() - offset.top + topPadding
                            }, 100, function() {
                            });
                        } else {
                            $sidebar.stop().animate({
                                marginTop: 0
                            });
                        }
                    });
    
                };
    

    if ($(window).width() > 767) part keeps the sidebar from scrolling if the viewport is wider than 767px. if($window.scrollTop() > $('h3').offset().top) { $sidebar.stop().css('marginTop', '680px'); } part is for when the top of the viewport hits the desired element, h3, the scrolling stops. That part must be first because the else if statement is always true! Then I just reduced the animation time to stop the lagging.