I want to div position to be fixed when document scroll and that div reached to 50px from top.
Please check the code below
HTML
<div id="main">
<div id="nav"></div>
<div id="left"></div>
<div id="right">
<div id="box1"></div>
<div id="box2"></div>
</div>
</div>
CSS
#main{ overflow:hidden; width:600px; height:900px; background:#afaaac; margin:0; padding:0; }
#nav{ width:600px; height:40px; background:#15bc44; position:fixed; margin:0; padding:0;}
#left{ overflow:hidden; width:400px; height:900px; background:#18769e; float:left; }
#right{ overflow:hidden; width:200px; height:900px; background:#bc1544; float:right; }
#box1{ float:right; width:150px; height:200px; display:block;background:#e34d2a; margin-bottom:20px; }
#box2{ float:right; width:150px; height:200px; display:block;background:#e34d2a; margin-bottom:20px; }
.box2{ position:fixed; margin-left:50px; margin-top:50px; }
JS
$(document).ready(function() {
var s = $("#box2");
var pos = s.position();
$(window).scroll(function() {
var windowpos = $(window).scrollTop() ;
//s.html("Distance from top:" + pos.top + "<br />Scroll position: " + windowpos);
if (windowpos >= pos.top) {
s.addClass("box2");
} else {
s.removeClass("box2");
}
});
});
This work but it will go to the top of the document and jump back 50px.
I also tried changing
$(window).scroll(function() { to
$(window).scroll(function() > 50 {
and
if (windowpos >= pos.top) { to if (windowpos >= 50) {
This all seems make position jump around. Please check the JSFiddle below
If anyone can point me out the correct way to do this, i will really appropriate it.