To determine if a block appears (at least 1 of its pixels, provided that the block enters the screen horizontally) on the screen when scrolling from top to bottom, it is enough to compare the sum of .scrollTop() and .height() for window with a vertical block offset relative to the top of the page .offset().top ):
$(function() { var blockTop = $('.second').offset().top; var CountUpFlag = 0; var $window = $(window); $window.on('load scroll', function() { var top = $window.scrollTop(); var height = $window.height(); if (top + height >= blockTop && CountUpFlag == 0) { CountUp(); CountUpFlag = 1; } }); function CountUp() { $('#animation').show(); } });
.first { height: 1500px; } .second { border: 1px solid; height: 200px; } #animation { position: fixed; display: none; }
<div id="animation">Time for animation</div> <div> <div class="first"></div> <div class="second"></div> <div class="first"></div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
When scrolling from the bottom up, you need to compare the sum of the vertical offset and the height of the block with the .scrollTop() for the window .
Also, instead of writing your own code, you can use the appropriate plugin. For example, jQuery.appear .