Search code examples
triggersscreencountervisible

How to trigger counter when become visible on the screen?


I got counter that counts from 0 to certain number. Now I need to activate counter when it become visible on the screen (some 10% from the top of the screen). I have no idea how to do this.

<div id="counter">
        <h2 id="counter1">0</h2>
        <i class="seperator"></i>
        <h3>{param_count-title}</h3>
</div>


<script type="text/javascript">
        $({countNum: $('#counter1').text()}).animate({countNum: {param_count-number}}, {
  duration: {param_duration},
  easing:'linear',
  step: function() {
    $('#counter1').text(Math.floor(this.countNum));
  },
  complete: function() {
    $('#counter1').text("{param_count-number}");
  }
});


Solution

  • demo: http://so.devilmaycode.it/how-to-trigger-counter-when-become-visible-on-the-screen

    you need a little bit of CSS like:

        #counter {
            top: -20%;
            left: 0;
            position: absolute;
            opacity: 0
        }
    

    then the Javascript part like :

        $('#counter').animate({
            top: '20%',
            opacity: 1
        }, 1000, function () {
            // YOUR CODE HERE
            var from = parseInt($('#counter h2').text()),
                to = $('#counter h3').text().length;
            $({
                countNum: from
            }).animate({
                countNum: to
            }, {
                duration: 1000,
                easing: 'linear',
                step: function () {
                    $('#counter h2').text(Math.floor(this.countNum));
                },
                complete: function () {
                    $('#counter h2').text("{param_count-number}");
                }
            });
            // EOF YOUR CODE
        });