Overview
We have a requirement in one of our projects to have counters that should be animated when it is within the viewport as well as on scroll in both directions. As we all know that the simplest way is to go to Google and search for some script that makes our job easy, we also did the same but we were unable to search for the same. Now, we don’t have any other option rather than generating it on our own.
Prerequisite
To initialize, we looked up for the script that help us to know that the particular element is within the viewport(user’s visible area of the site) and we succeeded in finding the one i.e Waypoints Inview. We have used that to implement this counters. Most primary requirement for this jquery library. You can download waypoints scripts from here.
Implementation
1) Implement the script for counter
Mostly we begin the easiest task that we are able to sail through. So we begin with script for the counter increment.
HTML:
<div id="inview-example" class="counters"> <div class="common-box"> <div class="counter-num"> <span class="timer" data-count="9">9</span> <span>+</span> </div> <div class="counter-text">Years Experience</div> </div> <div class="common-box"> <div class="counter-num"> <span class="timer" data-count="2200">2200</span> <span>+</span> </div> <div class="counter-text">Successful Projects</div> </div> <div class="common-box"> <div class="counter-num"> <span class="timer" data-count="80">80</span> <span>%</span> </div> <div class="counter-text">Repeated Clients</div> </div> <div class="common-box"> <div class="counter-num"> <span class="timer" data-count="200">200</span> <span>+</span> </div> <div class="counter-text"> Employees</div> </div> </div>
Script:
$('.timer').each(function () { var $this = $(this); var val = $(this).data('count'); jQuery({ Counter: 0 }).animate({ Counter: val }, { duration: 1000, easing: 'swing', step: function () { $this.text(Math.ceil(this.Counter)); } }); });
2) Implement waypoints
To begin with waypoints, we need to include scripts as stated in prerequisite. Then we created a function for it and initialized that function on load of the page.
function inviewExample() { var $example = $('#inview-example'); var inview; if ($example.length) { inview = new Waypoint.Inview({ element: $('#inview-example')[0], entered: function(direction) { // counter script that we have implemented in previous step } } $(window).on('load', function() { inviewExample(); });
3) Result
You can download the source code from here. The final result is as below.
Conclusion
I hope that this blog might be useful to you. I have implemented this with the help of my colleagues Richa and Amitsinh.