Markus Hayner
Markus Hayner

Reputation: 2959

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.

Upvotes: 4

Views: 17133

Answers (1)

areim
areim

Reputation: 3741

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

Upvotes: 8

Related Questions