Reputation: 7587
I have an one-page-style website and somewhere in the middle I have a few numbers as statistics. I try to make them counting until they reach the stats when a user find the div for the first time after refreshing the page. I don't have the option to use a plugin, so I am trying to do it with JQuery only.
Here is the code:
$(window).scroll(function(){
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $("#our-company").offset().top;
var elemBottom = elemTop + $("#our-company").height();
if ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)) {
start_count();
}
});
function start_count(){
$('.count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
}
The div with the id = our-company
is the one containing the stats and all the numbers are in a span with a class of class = count
. The problem in my code is that after I scrolled down on the stats and see the numbers counting, if I scroll up and down again, they start from the beginning. How can I make it run once?
Upvotes: 0
Views: 401
Reputation: 111
Why not just put a flag var ?
var alreadyRun = false;
[...]
if (alreadyRun == false && (elemBottom <= docViewBottom) && (elemTop >= docViewTop)) {
alreadyRun = true;
start_count();
}
[...]
Cheers
Upvotes: 1