Reputation: 555
I work on creating a count up number like in this link: Themeforest Link
But there are many problems:
First problem: I need to do animation when the element is shown in the view port.
Second problem: When I scroll again, the element number is animation from up to down and the duration is not working well. I don't know why this problem is occurs.
The code is below:
function countUp() {
$('.count').each(function () {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
}
$(function () {
"user strict";
$(window).scroll(function () {
console.log("scroll top=" + $(this).scrollTop());
console.log("div offset top=" + $("div").offset().top);
var scrolling = $(this).scrollTop(),
divoffset = $(".count").offset().top;
if (scrolling > divoffset - 300) {
countUp();
}
})
})
body{
height:4000px;
}
.count{
width:200px;
height:200px;
text-align:center;
line-height:200px;
border:1px solid #10f880;
margin:1000px auto 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="count">1000</div>
Note: I've tried this Stack Overflow suggestion, but I'd like to understand the idea, thank you:
Upvotes: 2
Views: 2548
Reputation: 1044
function countUp() {
$('.count').each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function(now) {
$(this).text(Math.ceil(now));
}
});
});
}
$(function() {
"user strict";
var bAnimate = true;
$(".count").css ("opacity", "0.0");
$(window).scroll(function() {
// console.log("scroll top=" + $(this).scrollTop());
// console.log("div offset top=" + $("div").offset().top);
var scrolling = $(this).scrollTop(),
divoffset = $(".count").offset().top,
screenBottom = scrolling + $(window).height(),
elemBottom = divoffset + $(".count").outerHeight (); //
if (screenBottom > elemBottom) {
if (bAnimate) {
$(".count").css ("opacity", "1.0");
countUp();
bAnimate = false;
}
}
})
})
body {
height: 4000px;
}
.count {
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
border: 1px solid #10f880;
margin: 1000px auto 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="count">1000</div>
Execute the function when bottom of the screen(window height) is greater than bottom of the element(top of element + outerHeight). Use boolean to stop the function from executing second time.
Upvotes: 3