Nrc
Nrc

Reputation: 9787

Scroll function

I'm trying to do a menu that moves up and down when I move the scroll. I'm close to it but when it moves it jumps a bit, the movement of the menu (div right) is not smooth. Anyone knows how to improve it?

(Of course it should not move horizontally and could not overlap the content on the left. Please see the example live here:http://jsfiddle.net/67ZFe/)

THE JQUERY:

$(function(){

    $(document).scroll(function(){
        var windowTop = $(window).scrollTop();
        $('#right').css('margin-top', (windowTop)  + 'px'); 
    });

})

THE CSS:

body {background-color: #f2f2f2;font-size: 13px;margin: 0;padding: 0;}
#wrapper {position: relative; margin:0 auto;width:700px;height:900px;background-color:#fff;}
#right {
    position: absolute;
    top: 40px;
    right:0px;
    width:200px;
    height:200px;
    background-color: red;
}
#text {
    position: absolute;
    left: 0px;
    width:400px;
    padding:40px;
}

THE HTML:

<div id="wrapper">
  <div id="text"> </div>
  <div id="right"> </div>
</div>

I have an example here: http://jsfiddle.net/67ZFe/

Upvotes: 0

Views: 93

Answers (2)

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

I might be missing something, but wouldn't it be easier to use an element with fixed position instead of moving the element all the time?

When an element uses fixed position, its position is determined in relation to the browser window, instead of the page. So the menu will always be placed at a certain position in relation to the top for instance, even if you scroll the page.

Using fixed positioning will be much more smooth than using a JavaScript-solution.

I would use something like:

#right {
   position: fixed;
   top: 50px; /* Or whatever suits you */
}

Upvotes: 0

Wes Cossick
Wes Cossick

Reputation: 2933

It may be better, and faster, to do this with a position:fixed; css attribute rather than with jQuery.

Upvotes: 2

Related Questions