0

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

http://jsfiddle.net/uGw2Z/2/

If anyone can point me out the correct way to do this, i will really appropriate it.

2
  • 3
    Output like this : jsfiddle.net/uGw2Z/3 ? Commented Jun 5, 2014 at 6:10
  • @Zword Thank you this works great. if you can add this as an answer i can select as the correct answer for others to see. Commented Jun 5, 2014 at 6:29

2 Answers 2

1

Just add a number inorder to remove jump : windowpos+54

Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. Work like a charm.
0

You need to change the css code in the .box2 like this:

.box2{position:fixed; top:50px; margin-left:50px}

check out this fiddle : JSFIDDLE

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.