Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Fixed floating element scrolling smoothly in Firefox and Chrome

I have a script that uses jQuery and CSS to position something at the top of the page when it scrolls. However, the bar looks like it's shaking when you scroll and it has been fixed to the top of the browser in Google Chrome and Mozilla Firefox. Why could this be?

I hope you can understand what I'm trying to describe. If not, copy and paste this code along with a jQuery library to see what I mean:

<style type='text/css'>
body {
    height:1000px;
    margin:0;
    padding:0;
}

#scroller {
    position:relative;
    top:60px;
    width:100%;
    background:#CCC;
    height:20px;
}
</style>

<script type='text/javascript'>
    $(window).load(function() {
        $(window).scroll(function() {
            if($(window).scrollTop()>60) {
              $('#scroller').css('top', $(window).scrollTop());
            }
        });
    });
</script>

<div id="scroller">Some controls</div>
like image 705
Callum Whyte Avatar asked Jan 27 '26 05:01

Callum Whyte


1 Answers

Use this:

$(window).load(function(){
    $(window).scroll(function(){
        if($(window).scrollTop()>60){
            $('#scroller').css('position', 'fixed');
            $('#scroller').css('top', 0);
        } else {
            $('#scroller').css('position', 'relative');
            $('#scroller').css('top', 60);
        }
    });
});

http://jsfiddle.net/nwellcome/6PGZE/1/

Rather than manipulating the top all the time, once it's supposed to stay at the top set "position" to "fixed" and top to 0, that way it doesn't have to wait for the javascript scroll event to fire to fix the position.

like image 199
nwellcome Avatar answered Jan 28 '26 18:01

nwellcome



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!