I have a counter which animates to a final number which is defined in the HTML. However I would like this animation to happen once it's in the viewport.
I have a fiddle here which shows how scrolling seems to effect the counter number.
$(document).ready(function() {
$(function($, win) {
$.fn.inViewport = function(cb) {
return this.each(function(i, el) {
function visPx() {
var H = $(this).height(),
r = el.getBoundingClientRect(),
t = r.top,
b = r.bottom;
return cb.call(el, Math.max(0, t > 0 ? H - t : (b < H ? b : H)));
}
visPx();
$(win).on("resize scroll", visPx);
});
};
}(jQuery, window));
$(".fig-number").inViewport(function(px) {
$(this).each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 1000,
step: function(now) {
$(this).text(Math.ceil(now));
}
});
});
});
});
I've tried multiple things but I cant seem to achieve what I'm after.
$(document).ready(function() {
$(function($, win) {
$.fn.inViewport = function(cb) {
return this.each(function(i, el) {
function visPx() {
var H = $(this).height(),
r = el.getBoundingClientRect(),
t = r.top,
b = r.bottom;
return cb.call(el, Math.max(0, t > 0 ? H - t : (b < H ? b : H)));
}
visPx();
$(win).on("resize scroll", visPx);
});
};
}(jQuery, window));
$(".fig-number").inViewport(function(px) {
$(this).each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 1000,
step: function(now) {
$(this).text(Math.ceil(now));
}
});
});
});
});
html,
body {
height: 100%;
}
#upper-push {
height: 100%;
width: 100%;
display: block;
background: red;
color: white;
}
<div id="upper-push">
Scroll down
</div>
<div id="numbers">
<span class="fig-number">25</span>
<span class="fig-number">78</span>
</div>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…