samedi 25 avril 2015

Scroll to div then fix it to top of page


I currently have a div (#sticky) within the right bar of my page and would like to fix it to the top of the page once I scroll to it. The div (#sticky) I want fixed to the top of the page sits about 1000px down the page.

HTML:

<div id="right-bar">
  <div id="sticky-anchor"></div>
  <div id="sticky"></div>
</div>

CSS:

#right-bar {
  display: inline-block;
  float: left;
  width: 336px;
  height: 10000px;
  margin-left: 15px;
}

#sticky {
  display: block;
  width: 334px;
  height: 600px;
  background-color: white;
  border: 1px solid #e5e5e5;
  margin-top: 15px;
}

#sticky .stick {
  position: fixed;
  top: 0;
  z-index: 10000;
}

JAVASCRIPT: (within head tags)

<script>
  function sticky_relocate() {
  var window_top = $(window).scrollTop();
  var div_top = $('#sticky-anchor').offset().top;
  if (window_top > div_top) {
    $('#sticky').addClass('stick');
  } else {
    $('#sticky').removeClass('stick');
  }
}

$(function () {
  $(window).scroll(sticky_relocate);
  sticky_relocate();
});
</script>

Not quite sure what I am doing wrong, but once I scroll to the div, I bypass it without it getting stuck to the top of the page.

Any and all help is appreciated!


Aucun commentaire:

Enregistrer un commentaire