codice:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Documento senza titolo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style type="text/css">
html,body{
margin:0;
padding:0;
}
#pre{
background:#eee;
height:1500px;
padding:33px;
}
#target{
background:#666;
color:#fff;
height:600px;
}
#scroll_amount{
position:fixed;
top:15px;
right:15px;
background:rgba(0,0,0,0.5);
color:#fff;
width:250px;
padding:40px;
}
#scroll_amount:before{
content:'Scroll pagina in pixel';
font-weight:bold;
display:block;
margin-bottom:5px;
}
#shiva
{
width: 100px;
height: 100px;
background: red;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
float:left;
margin:5px;
}
.count
{
line-height: 100px;
color:white;
margin-left:30px;
font-size:25px;
}
</style>
<script type="text/javascript">
var target_top, screen_height, seen;
$(function(){
seen=false;
target_top=$('#target').offset().top;
screen_height=$(window).height();
$('#pre').append('<p>Posizione di #target: '+target_top+'px</p>');
$('#pre').append('<p>Altezza finestra: '+screen_height+'px</p>');
$('#pre').append('<p>Quantità di scroll per far apparire #target: '+Number(target_top-screen_height)+'px</p>');
});
$(window).scroll(function(){
var scroll_amount=$(window).scrollTop();
$('#scroll_amount').text(scroll_amount+'px');
if(scroll_amount>=(target_top-screen_height)){
if(!seen){
increment();
seen=true;
}
$('#scroll_amount').append('<p><strong>#target è visibile!</strong></p>');
}else{
$('#scroll_amount p').remove();
}
});
function increment(){
$('.count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
}
</script>
</head>
<body>
<div id="pre"><h1>Above the fold</h1></div>
<div id="target"><div id="shiva"><span class="count">1000</span></div></div>
<div id="scroll_amount">0px</div>
</body>
</html>
Ho usato la variabile seen per eseguire l'animazione una sola volta.