Hi there WorldNews,
my example uses…
element.offsetTop+element.offsetHeight-window.innerHeight
…to make the “number auto increment” start only when it’s
container is fully visible, and,unlike your example, it also
works for various window height dimensions.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">
<title>untitled document</title>
<style media="screen">
body {
margin:0.5em;
}
#info {
padding: 3em 0;
margin: auto;
border: 0.1em solid #ccc;
background-color: #fff;
box-sizing: border-box;
text-align: center;
}
.newposition {
position: fixed;
left: 0.5em;
right: 0.5em;
top: 0;
}
#number {
display:inline-block;
padding:0.5em;
border: 0.06em dotted #ccc;
font-size: 2em;
}
</style>
</head>
<body>
<div class="box"></div>
<div id="info"><span id="number">0</span></div>
<div class="box"></div>
<script>
(function() {
'use strict';
var el=document.getElementById('info');
var num=document.getElementById('number');
var el2=document.getElementsByClassName('box')[0].style;
var infotop=el.offsetTop;
var numtop=num.offsetTop;
var numhgt=num.offsetHeight;
var winhgt=window.innerHeight;
var c=0;
var st;
var delay=25;
var y;
window.onresize=function() {
if(y<infotop){
el2.marginBottom=0;
}
infotop=el.offsetTop;
numtop=num.offsetTop;
winhgt=window.innerHeight;
el.className='';
};
window.onscroll=function() {
if(y<infotop){
el2.marginBottom=0;
}
y=window.pageYOffset;
if(y>numtop+numhgt-winhgt){
if(c===0) {
countup();
}
}
if(y>infotop) {
el.className='newposition';
el2.marginBottom=el.offsetHeight+'px';
}
else {
el.className='';
el2.marginBottom=0;
}
};
function countup() {
if(c>1000) {
clearTimeout(st);
return;
}
num.innerHTML=c;
c++;
st=setTimeout(countup,delay);
}
}());
</script>
</body>
</html>
coothead