javascript - Show Div when scrolled to top edge not bottom edge -
i using code here need show div when top scrolls view not bottom, how can 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); } }); }); });
simple fix. trick .animate()
when hit top. right now, you're using
var bottom_of_object = $(this).position().top + $(this).outerheight()
you don't need $(this).outerheight()
because increases y position need scroll height of div
. remove 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)
Comments
Post a Comment