Start Counting After Scroll on Specific Element

Sometimes it’s important to do some activities when a specific¬†element is visible on the web page. So something needs to be trigger when that element is showing on the web page. Suppose you want to start counting after scroll on that specific element. Here is the code for that.

HTML CODE:
<div class="container">
  <h2 class="well well-lg" style="margin-top: 200px;">Scroll Down</h2>
  <h2 class="well well-lg" style="margin-top: 200px;">Scroll Down</h2>
  <div class="jumbotron text-center" style="margin-top: 200px;">
    <div class="container">
      <div class="col-lg-3">
        <h2>Total Sales</h2>
        <h1 class="counter">967</h1>
      </div>
      <div class="col-lg-3">
        <h2>Total Sales</h2>
        <h1 class="counter">967</h1>
      </div>
      <div class="col-lg-3">
        <h2>Total Sales</h2>
        <h1 class="counter">967</h1>
      </div>
      <div class="col-lg-3">
        <h2>Total Sales</h2>
        <h1 class="counter">967</h1>
      </div>
    </div>
  </div>
</div>
JAVASCRIPT CODE:
function isCounterElementVisible($element) {
  var topView = $(window).scrollTop();
  var botView = topView + $(window).height();
  var topElement = $element.offset().top;
  var botElement = topElement + $element.height();
  return ((botElement <= botView) && (topElement >= topView));
}

$(window).scroll(function() {
  $(".counter").each(function() {
    isOnView = isCounterElementVisible($(this));
    if (isOnView && !$(this).hasClass('visibled')) {
      $(this).addClass('visibled');
      $(this).prop('Counter', 0).animate({
        Counter: $(this).text()
      }, {
        duration: 3000,
        easing: 'swing',
        step: function(now) {
          $(this).text(Math.ceil(now));
        }
      });
    }
  });
});

See Demo:

Published by

Sohel Rana

PHP Programmer, Software Engineer & Technology lover

2 thoughts on “Start Counting After Scroll on Specific Element”

  1. Hi im Hessel, im new to PHP, understanding HTML and CSS but need to learn PHP for my study International Business IT & Management. The way you explain thing is really helpful! Reading this from The Netherlands. Thanks and keep up this blog, it helps alot!

Leave a Reply

Your email address will not be published. Required fields are marked *