I'm currently working on a Counter
that shows some stats for my Homepage.
Here's the Script I'm using:
$('.count-1, .count-2, .count-3, .count-4').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 5000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
Now I only want to run this animation if the counter comes in the screen ... So I got this Script:
$(document).ready(function () {
var windowHeight = $(window).height(),
gridTop = windowHeight * -10,
gridBottom = windowHeight * .9;
$(window).on('scroll', function () {
$('.class').each(function () {
var thisTop = $(this).offset().top - $(window).scrollTop();
if (thisTop > gridTop && (thisTop + $(this).height()) < gridBottom) {
// run this if .class gets in viewpoint
} else {
// run this else
}
});
});
});
So I put both of 2 scripts together to this:
$(document).ready(function () {
var windowHeight = $(window).height(),
gridTop = windowHeight * -10,
gridBottom = windowHeight * .9;
$(window).on('scroll', function () {
$('.count-1, .count-2, .count-3, .count-4').each(function () {
var thisTop = $(this).offset().top - $(window).scrollTop();
if (thisTop > gridTop && (thisTop + $(this).height()) < gridBottom) {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 5000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
} else {
}
});
});
});
Now if I scroll down on my page, the counter starts running when it gets in the screen (which is exakly what I wanted) BUT when the counter finishes, the counter starts to count backwards untill .count-1
, .count-2
... is at 1
. And even if I scroll up and down again ... the counter still stays at 1
. Sometimes the 1
changes to a 2
or 3
but than quickly goes down to a 1
again.
Here's the snippet:
$(document).ready(function () {
var windowHeight = $(window).height(),
gridTop = windowHeight * -10,
gridBottom = windowHeight * .9;
$(window).on('scroll', function () {
$('.count-1, .count-2, .count-3, .count-4').each(function () {
var thisTop = $(this).offset().top - $(window).scrollTop();
if (thisTop > gridTop && (thisTop + $(this).height()) < gridBottom) {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 5000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
} else {
}
});
});
});
/* just for some scrolling */
#container {
margin-top: 1000px;
margin-bottom: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Scroll down!</p>
<div id="container">
<div class="count-1">200</div>
<div class="count-2">100</div>
<div class="count-3">50</div>
<div class="count-4">4</div>
</div>
Where is the mistake?