I have in my document five div, I want that after scrolling the div's become fixed when they reach a specific position (100px for example) but some div become fixed only when they exceed that position. I tried with 0px it's the same things but the problem is more visible with 100px can some one help me to fix this problem
css
#f1{
width:600px;
z-index:1;
}
#f2{
width:600px;
z-index:2;
}
#f3{
width:600px;
z-index:3;
}
#f4{
width:600px;
z-index:4;
}
#f5{
width:600px;
z-index:5;
}
.fixed{
position:fixed;
top:100px;
}
js
$( document ).ready(function() { var f1 = $('#f1').offset().top ; var f2 = $('#f2').offset().top ; var f3 = $('#f3').offset().top ; var f4 = $('#f4').offset().top ; var f5 = $('#f5').offset().top ; $(window).scroll(function (event) { var y = $(this).scrollTop()+100; if (y >= f1) { $('#f1').addClass('fixed'); } else { $('#f1').removeClass('fixed'); } if (y >= f2) { $('#f2').addClass('fixed'); } else { $('#f2').removeClass('fixed'); } if (y >= f3) { $('#f3').addClass('fixed'); } else { $('#f3').removeClass('fixed'); } if (y >= f4) { $('#f4').addClass('fixed'); } else { $('#f4').removeClass('fixed'); } if (y >= f5) { $('#f5').addClass('fixed'); } else { $('#f5').removeClass('fixed'); } }); });
html
<div style="width:600px; margin:0 auto; background:#ccc">
<p>
some long text here
</p>
<div id="f1" style="background:#000; color:#fff">
div 1
</div>
<p>
some long text here
</p>
<div id="f2" style="background:#000; color:#fff">
div 2
</div>
<p>
some long text here
</p>
<div id="f3" style="background:#000; color:#fff">
div 3
</div>
<p>
some long text here
</p>
<div id="f4" style="background:#000; color:#fff">
div 4
</div>
<p>
some long text here
</p>
<div id="f5" style="background:#000; color:#fff">
div 5
</div>
<p>
some long text here
</p>
</div>
you can see the result here http://jsfiddle.net/hPs6p/
I found the issue by my self so thank you all
js
$( document ).ready(function() { $(window).scroll(function (event) { var y = $(this).scrollTop()+100; var f1 = $('#f1').offset().top ; var f2 = $('#f2').offset().top ; var f3 = $('#f3').offset().top ; var f4 = $('#f4').offset().top ; var f5 = $('#f5').offset().top ; if (y >= f1) { $('#f1').addClass('fixed'); } else { $('#f1').removeClass('fixed'); } if (y >= f2) { $('#f2').addClass('fixed'); } else { $('#f2').removeClass('fixed'); } if (y >= f3) { $('#f3').addClass('fixed'); } else { $('#f3').removeClass('fixed'); } if (y >= f4) { $('#f4').addClass('fixed'); } else { $('#f4').removeClass('fixed'); } if (y >= f5) { $('#f5').addClass('fixed'); } else { $('#f5').removeClass('fixed'); } }); });
this js solve the problem
the offset of div1,div2,div3,div4 and div 5 was caluculated one time before firing the scroll event and when div1 become fixed it is out of flow and so for other div the solution is to calculate the div's offset in the scrolling event to get the real offset after some elements become out of the flow