JSFiddle - React, Tailwind, and code Playground
HTML
<div class="large-space"></div>
<div id="shiva"><span class="count" data-total="1000">0</span></div>
CSS
#shiva {
width: 100px;
height: 100px;
}
.count {
line-height: 100px;
color: black;
margin-left: 30px;
font-size: 25px;
}
.large-space {
height: 600px;
}
JavaScript
$(function () {
$(window).on("scroll", function () {
var shivaElement = $('#shiva'),
span = shivaElement.find('.count'),
fire = isOnScreen(span);
if(fire){
$({
Counter: Number(span.text())
}).animate({
Counter: span.attr('data-total')
}, {
duration: 2000,
easing: 'swing',
step: function () {
$(span).text(Math.ceil(this.Counter));
},
});
}
});
});
function isOnScreen(element) {
var viewPortHeight = $(window).height(), // Viewport Height
scrollTop = $(window).scrollTop(), // Scroll Top
currElementPosY = $(element).offset().top,
elementHeight = $(element).height();
return (currElementPosY + elementHeight > scrollTop && currElementPosY < (viewPortHeight + scrollTop))
}