Timothy Timothy - 3 months ago 10
CSS Question

Show Div when scrolled to top edge not bottom edge

I am using the code from here but i need it to show the div when the top scrolls into view not the bottom, how can i achieve this?
JS Fiddle

$(document).ready(function() {
$(window).scroll( function(){
$('.hide').each( function(i){
var bottom_of_object = $(this).position().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
if( bottom_of_window > bottom_of_object ){
$(this).animate({'opacity':'1'},500);
}
});

});

});

Answer

Simple fix. The trick is to .animate() when you actually hit the top. Right now, you're using

var bottom_of_object = $(this).position().top + $(this).outerHeight()

You don't need $(this).outerHeight() because that increases the y position to which you need to scroll by the height of the div. Just remove it so that you have

var top_of_object = $(this).position().top

$(document).ready(function() {
  $(window).scroll(function() {
    $('.hide').each(function(i) {
      var bottom_of_object = $(this).position().top
      var bottom_of_window = $(window).scrollTop() + $(window).height()
      
      if (bottom_of_window > bottom_of_object)
        $(this).animate({ opacity: '1' }, 500)
    })
  })
})
#container { height: 2000px }
#container div { background-color: gray; margin: 20px; padding: 80px }
.hide { opacity: 0 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div>shown</div>
  <div>shown</div>
  <div>shown</div>
  <div>shown</div>
  <div>shown</div>
  <div>shown</div>
  <div class="hide">Fade In</div>
  <div class="hide">Fade In</div>
  <div class="hide">Fade In</div>
  <div class="hide">Fade In</div>
  <div class="hide">Fade In</div>
</div>

fiddle (for posterity)