Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery fixing a side bar while scrolling, until bottom

This code is taken from waypointarts.com and it's suppose to create a Fixing a side bar while scrolling, until bottom. problem is when right div is populated the left div's height even though set to 100# stay fixed to certain height, window/screen or something. how can I set it so its 100% height or equivalent to right div's height.

HTML Header

<div id="wrapper">

  <div id="left">

    <div id="sidebar">

      Sidebar Content

    </div>

  </div>

  <div id="right">

    This is the text of the main part of the page.

  </div>

  <div class="clear"></div>

</div>

<div id="footer">Footer</div>

CSS

#header {
  background: #c2c2c2;
  height: 50px
}

#wrapper {
  width: 500px
}

#left {
  background: #d7d7d7;
  position: absolute; /* IMPORTANT! */
  width: 150px;
  height: 100%
}

#right {
  position: relative;
  width: 350px;
  float: right
}

#sidebar {
  background: #0096d7;
  width: 150px;
  color: #fff
}

.clear {
  clear: both
}

#footer {
  background: #c2c2c2
}

JAVASCRIPT

$(document).ready(function () {

    var length = $('#left').height() - $('#sidebar').height() + $('#left').offset().top;

    $(window).scroll(function () {

        var scroll = $(this).scrollTop();
        var height = $('#sidebar').height() + 'px';

        if (scroll < $('#left').offset().top) {

            $('#sidebar').css({
                'position': 'absolute',
                'top': '0'
            });

        } else if (scroll > length) {

            $('#sidebar').css({
                'position': 'absolute',
                'bottom': '0',
                'top': 'auto'
            });

        } else {

            $('#sidebar').css({
                'position': 'fixed',
                'top': '0',
                'height': height
            });
        }
    });
});

Image from waypoitsarts.com:

Image from waypoitsarts.com

like image 741
Francis Chibaye Avatar asked Jan 30 '14 04:01

Francis Chibaye


1 Answers

I think your script is working fine, probably the problem is on your CSS. In order to properly contain a position:absolute; element you should set its parent element ('#wrapper') to position:relative.

See the demo on this jsfiddle: jsfiddle.net/J62Cp/

like image 177
Mark S Avatar answered Nov 15 '22 09:11

Mark S