Last active
June 11, 2018 19:56
-
-
Save stevedya/4d2cf70e9dfa2005f283e6b4366ef69f to your computer and use it in GitHub Desktop.
jQuery - Number Counter with Commas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //Call the function on scroll | |
| $(window).scroll(numberCounter); | |
| //Check if in viewport function | |
| function inViewport(el, val) { | |
| var docViewTop = $(window).scrollTop(); | |
| var docViewBottom = docViewTop + $(window).height(); | |
| var elTop = $(el).offset().top; | |
| var elBottom = elTop + $(el).height(); | |
| return ((elTop + val <= docViewBottom)); | |
| } | |
| //Counter Function | |
| function numberCounter() { | |
| if (inViewport($('.stat-number'), 100)) { | |
| $('.stat-number').not('.counted').each(function () { | |
| var $this = $(this); | |
| $({Counter: 0}).animate({Counter: $this.text()}, { | |
| duration: 1000, | |
| easing: 'swing', | |
| step: function () { | |
| $this.addClass('counted'); | |
| $this.text(commaSeparateNumber(Math.round(this.Counter))); | |
| } | |
| }); | |
| }); | |
| } | |
| } | |
| //Add Commas Function | |
| function commaSeparateNumber(val) { | |
| while (/(\d+)(\d{3})/.test(val.toString())) { | |
| val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"); | |
| } | |
| return val; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment