Search code examples
javascriptcsssidebarsticky

Sticky sidebar doesn't stop scrolling


I have a sticky sidebar on my page using the following script:

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

The problem is that it should stop scrolling when it reaches the Middle Block Div. At the moment it doesn't stop scrolling and it pushes all the rest of the content down. Is there a way to fix this?

- DEMO -

Thank you.


Solution

  • You need to get the position of .middle-block and stop the sidebar from scrolling at that point (minus the height of the sidebar).

    Change your jQuery function to:

    $(function() {
        var offset = $("#sidebar").offset();
        var mbOffset = $(".middle-block").offset();
        var mbPos = mbOffset.top - $("#sidebar").outerHeight() - 30; /*30px extra space*/
        var topPadding = 15;
        $(window).scroll(function() {
            if ($(window).scrollTop() > offset.top ) {
                if(  $(window).scrollTop() < mbPos ) {
                    $("#sidebar").stop().animate({
                        marginTop: $(window).scrollTop() - offset.top + topPadding
                    });
                }
            } else {
                $("#sidebar").stop().animate({
                    marginTop: 0
                });
            };
        });
    });
    

    Updated Pen