Search code examples
jqueryhtmlcssscrollsidebar

stops sidebar scrolling when its reach bottom of the page


I am working on a site which has a sticky sidebar. The sidebar will only fix on a scrolling window.

The problem is, when I scroll window down and reach bottom of the page, the sidebar will overlap the footer because the sidebar is fixed.

I want, when the user reaches the bottom of the page, the sidebar to stop scrolling and, if user is scrolling top of the page, it should start scrolling again.

You can check my code below or you can check fiddle here.

SCRIPT

<script>
$(window).scroll(function(){

        var contPos = $('.sidebar').offset().top;       

        var containerHeight = $('.container').height();

        var heightOfWindow = $('body').height();            
        var topOfWindow = $(window).scrollTop();

            if (contPos < topOfWindow) {
                $('.sidebar').css('margin-top',''+topOfWindow+'px');

            }
    }); 


</script>

HTML

<div class="header">Header</div>
<div class="sidebar">asd</div>
<div class="container">Contaier</div>
<div class="footer">Footer</div>

CSS

.header{height:100px; text-align:center; font-size:35px; color:#000; background:#999;}
.container{overflow:auto; padding:15px; background:#CCC; height:1000px; margin:0 0 0 300px;}
.sidebar{width:300px; height:700px; float:left; background:red;}
.footer{height:100px; text-align:center; font-size:35px; color:#000; background:#999;}

Solution

  • I guess you'll have to write a JS code that would detect if the sidebar is at the top, bottom or in the middle of the page. Then you could set a specific css class "bottom", "top",.. and set the right position between fixed/absolute.

    Here is how I would have done it:

    http://jsfiddle.net/w6G7Z/1/