Check out my code snippet on this JSFiddle link.
const ratingcount = document.querySelectorAll('.ratingcount');
const totalratingcounter = ratingcount.length;
var stopNow = totalratingcounter
countEach()
$(window).on('scroll', function(e) {
countEach()
})
function countEach() {
$('.ratingcount').each(function() {
if (showOnScreen(this) && $(this).attr('show') != 'false' && stopNow != 0) {
console.log($(this).text())
console.log($(this).attr('show'))
$(this).attr('show', 'false')
numberAnimate(this)
stopNow = stopNow - 1;
} else if (!showOnScreen(this)) {
$(this).attr('show', 'true')
}
})
}
function showOnScreen(target) {
if ($(window).scrollTop() + $(window).height() >= $(target).offset().top)
return true;
else
return false;
}
function numberAnimate(target) {
var $this = $(target);
jQuery({
Counter: 0
}).animate({
Counter: $this.text()
}, {
duration: 1000,
easing: 'swing',
step: function() {
$this.text(this.Counter.toFixed(1));
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>
Follow my steps, Scroll down to middle
</h1>
<span class="ratingcount">5.6</span><br/>
<span class="ratingcount">5.6</span>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<span class="ratingcount">5.6</span><br/>
<span class="ratingcount">5.6</span>
<h1>NOW SCROLL UP AGAIN and then scroll down
</h1>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<h1>
Now see this is not working
</h1>
<span class="ratingcount">5.6</span><br/>
<span class="ratingcount">5.6</span>
A common issue arises when using the following code:
const ratingcount = document.querySelectorAll('.ratingcount');
const totalratingcounter = ratingcount.length;
This code snippet calculates the quantity of elements with the class name ratingcount
.
Furthermore, the script halts the animation after each instance has been animated based on the class count.
var stopNow = totalratingcounter
The challenge lies in how a single number can animate multiple times while others cannot due to the scroll behavior.
For example: If you scroll down to a number in the middle, it will trigger the animation. However, upon scrolling back up and down again, the middle number animates once more, whereas the bottom number does not.