0

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);     
            }   
        }); 

    });

});
Community
  • 1
  • 1
Timothy
  • 1,128
  • 1
  • 14
  • 28

1 Answers1

2

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)

royhowie
  • 11,075
  • 14
  • 50
  • 67
  • @Timothy Explain. `40px` from the top of what? – royhowie Aug 17 '14 at 23:59
  • from the top of the div that's fading in – Timothy Aug 17 '14 at 23:59
  • @Timothy Do you want the div to fade in 40px before the bottom of the window hits the div or 40px after the bottom of the window passes the top of the div? Essentially, this [picture](http://i.imgur.com/wG4wLcT.png?1)—point A or point B? – royhowie Aug 18 '14 at 00:03
  • 2
    @Timothy then use `var top_of_object = $(this).position().top + 40`. Here's a [fiddle](http://jsfiddle.net/Luxelin/x6k4ynyk/). – royhowie Aug 18 '14 at 00:08