I have a simple counter, which when in viewport, I want it to count up to a set number.
However, I have two issues...
Function declaration for reference:
function numberCounter() {
$('.counter').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({
countNum: $this.text()
}).animate({
countNum: countTo
},
{
duration: 1500,
easing: 'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
}
});
});
};
Approach 1 isInViewport()
:
With the following code block, the function is being executed for every pixel scrolled within the div. This results in the counter jittering and not count up unless the user stops scrolling.
$(window).on(' scroll', function() {
if ($('.numberTicker').isInViewport()) {
console.log("test");
numberCounter();
$(window).off('resize scroll');
}
});
Approach 2 visible()
:
To resolve the above, I thought checking if the div is visible on viewport will execute the function once, however, the counter doesn't seem to work at all with this?
jQuery(document).ready(function($){
var ticker = $('.numberTicker');
if(ticker.visible(true)) {
numberCounter();
}
});
Where am I going wrong?
Full demo:
function numberCounter() {
$('.counter').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({
countNum: $this.text()
}).animate({
countNum: countTo
},
{
duration: 1500,
easing: 'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
}
});
});
};
jQuery(document).ready(function($){
var ticker = $('.numberTicker');
if(ticker.visible(true)) {
numberCounter();
}
});
// $(window).on(' scroll', function() {
// if ($('.numberTicker').isInViewport()) {
// console.log("test");
// numberCounter();
// $(window).off('resize scroll');
// }
// });
.spacer {
height: 400px;
background-color: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- is visible plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-visible/1.2.0/jquery.visible.min.js"></script>
<div class="spacer">scroll down</div>
<div class="numberTicker">
<h3 class="counter" data-count="50">50</h3>
</div>