Search code examples
jquerycsshtmlfixedsticky

multiple divs with fixed position and scrolling


I have 4 divs and I want to scroll down and cover all those divs. But... keeping the current div with fixed position on top of the browser

This is working great only scrolling down. But when I scroll up fails.

You can check this fiddle http://jsfiddle.net/rtSKj/ for a demo

This is the js code

$(document).ready(function() {
    $(window).scroll(function () {

        var scrollY = $(window).scrollTop();

        if(scrollY>=500){
            $('#block2').css({'position': 'fixed', 'margin-top': 0});
            $('#block3').css({'margin-top': '1000px'});
        }

        if(scrollY>=1000){
            $('#block3').css({'position': 'fixed', 'margin-top': 0});
            $('#block4').css({'margin-top': '1500px'});
        }

    });

});

note: the height of the divs is: 500px;

Should I consider the scroll direction to fix the behavior?


Solution

  • You need to 'reset' the position and margin-top.

    if(scrollY<500) {
      $('#block2').css({'position': 'relative', 'margin-top': '500px'});
    }
    if(scrollY<1000) {  
      $('#block3').css({'position': 'relative','margin-top': '1000px'});
    }
    

    See updated fiddle: http://jsfiddle.net/rtSKj/14/