Last active
March 1, 2016 04:41
-
-
Save raphaelchaib/5ea8a7b8cbecb86c3444 to your computer and use it in GitHub Desktop.
JavaScript: Animate counter on document scroll
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
| // statistics counter animation | |
| var counterFx = function counterFx(element) { | |
| var dfd = element.map(function(i, el) { | |
| var data = parseInt(this.dataset.value.replace(/[\.,]+/g, '')); | |
| var props = { | |
| "from": { | |
| "count": 0 | |
| }, | |
| "to": { | |
| "count": data | |
| } | |
| }; | |
| return $(props.from).animate(props.to, { | |
| duration: 1000 * 3, | |
| step: function(now, counterFx) { | |
| $(el).text(Math.ceil(now)); | |
| }, | |
| complete: function() { | |
| if (el.dataset.sym !== undefined) { | |
| el.textContent = el.textContent.concat(el.dataset.sym) | |
| } | |
| } | |
| }).promise(); | |
| }).toArray(); | |
| // return jQuery promise when all animations complete | |
| return $.when.apply($, dfd); | |
| }; | |
| var counterFxReset = function counterFxReset(el) { | |
| // do stuff when window `.scrollTop()` > el | |
| $that = $(this); | |
| console.log('scrollTop', $that.scrollTop()); | |
| $(el).each(function(i, v) { | |
| console.log('v', $(v).offset().top); | |
| console.log('scroll', ($that.scrollTop() + $that.height())); | |
| if (($that.scrollTop() + $that.height()) > $(v).offset().top) { | |
| // turn off scroll event so `counterFx` not called | |
| // during ongoing animation | |
| $that.off("scroll"); | |
| // when all animations complete | |
| counterFx($(v)); | |
| } | |
| }) | |
| }; | |
| // if `counterFx` should only be called once , | |
| // change `.on()` to `.one()` , | |
| // remove `.then()` callback following `counterFx()` | |
| // within `counterFxReset` | |
| $(window).on("scroll", function() { | |
| counterFxReset($('.statistics .counter')) | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment