This code make the counter/animation start when in view, but I would like for it to restart when scrolling out of view and then in view again. Can’t seem to solve it.
If you would like to see it live link here – scroll down to the bottom just before the footer.
https://easyrecycle.dk/Serviceomraader.html
var a = 0;
$(window).scroll(function() {
var oTop = $('#counter').offset().top - window.innerHeight;
if (a == 0 && $(window).scrollTop() > oTop) {
$('.counter-value').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({
countNum: $this.text()
}).animate({
countNum: countTo
},
{
duration: 3000,
easing: 'swing',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
//alert('finished');
}
});
});
a = 1;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="counter">
<div class="counter-container">
<div class="counter-box">
<div class="counter-value" data-count="30">0</div>
<span></span>
<p>Antal medarbejdere</p>
</div>
<div class="counter-box">
<div class="counter-value" data-count="51000">0</div>
<span></span>
<p>Processeret udstyr i KG pr. md.</p>
</div>
<div class="counter-box">
<div class="counter-value" data-count="51">0</div>
<span></span>
<p>Antal afhentninger pr. md.</p>
</div>
</div>
</div>
2
Answers
As you can see from my example below, i add a simple
if
(if is not in view) and reset the text/variable.Don’t use the
.scroll()
Event listener. It’s a performance killer. Same goes for JavaScript’s "scroll" EventListener – if used to perform heavy tasks. Actually you don’t need jQuery at all.Your task basically involves the use of:
counterStart()
function (triggered on viewport enter) that uses requestAnimationFrame — the most performant way to handle animations on the web.counterStop()
function (triggered on viewport exit) that cancels the AnimationFrame and resets the element counter back to itsstart
value.0.0 ... 1.0
) in order to retrieve the easing value to be used to derive your integers/counters.For a better understanding of the above main two chunks of code head to their original base answers which I basically reused and adapted:
with the basic differences being:
counter
function I passed the linear fraction of time into the easing functionif .. else
block; theelse
used to reset the element’stextContent
back to "0" (or anystart
value).Sorry for not using jQuery as I probably would’ve years ago, but hopefully you learned something exciting and new. If some parts are not completely clear, feel always free to ask.