Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 828
Nesta Avatar asked Oct 19 '22 14:10

Nesta


2 Answers

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

like image 187
LinkinTED Avatar answered Oct 27 '22 10:10

LinkinTED


you have check if Sidebar has been moved to Middle Box, if so just stop the sidebar to animate. like this :

$(function() {
            var offset = $("#sidebar").offset();
            var boxOffset = $(".middle-block").offset().top;
            var sidebarHeight = parseInt($("#sidebar").outerHeight());
            var topPadding = 15;
            $(window).scroll(function() {
                if ($(window).scrollTop() > offset.top) {
                    if(($(window).scrollTop()+sidebarHeight)<boxOffset){
                    $("#sidebar").stop().animate({
                        marginTop: $(window).scrollTop() - offset.top + topPadding
                    });
                    }
                } else {
                    $("#sidebar").stop().animate({
                        marginTop: 0
                    });
                };
            });
        });

check it live here: jsfiddle

like image 37
lokeshpahal Avatar answered Oct 27 '22 11:10

lokeshpahal