jake jake - 3 months ago 7
CSS Question

Make the side div follow after certain scroll

Right now the div on the right follows the scroll all the time. If I want it to start following the scroll when the page is scrolled to the top of the div, and make it remain there when scrolled up, what more do I need to do?

jsfiddle

$(window).scroll(function(){
var scrollTop = $(window).scrollTop();
$('.mSidebar').css( "top", scrollTop + 400 );
console.log(scrollTop);
});

Answer

Use like this :

$(document).ready(function(){

    $(window).scroll(function(){

        if($(document).scrollTop() > 400) {
            var newPos = $(document).scrollTop() + 400 ;
            $('.mSidebar').css( {top:newPos});
        }

        else {
            $('.mSidebar').css( {top:400});
        }
    })
})