Categories
Career Java Script Tips and Tricks

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.

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:

By Sohel Rana

PHP Programmer, Software Engineer & Technology lover

Leave a Reply

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