Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to float a div on scroll?

I try to float 2 divs when I am scrolling but is going to show only the right div on top of left one. Any idea how to fix this?

HTML

<body>
        <div id="scroller-left">Some controls left</div>
        <div id="scroller-right">Some controls right</div>
</body>

CSS

body{
            height:2000px;
            width: 100%;
            margin:0;
            padding:0;
        }
        #scroller-left{
            float: left;
            background:#CCC;
        }
        #scroller-right{
            float: right;
            background:#CCC;
        }

JavaScript

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

Jsfiddle
https://jsfiddle.net/q0fa81hf

thank you.

like image 537
Markus Hayner Avatar asked Sep 15 '25 13:09

Markus Hayner


1 Answers

I think, there is no need for JS solution in this case. My solution CSS only:

body {
    height:2000px;
    width: 100%;
    margin:0;
    padding:0;
}

#scroller-left{
    position: fixed;
    left: 0;
    background:#CCC;
}

#scroller-right{
    position: fixed;
    right: 0;
    background:#CCC;
}

JSFiddle

like image 98
areim Avatar answered Sep 17 '25 02:09

areim