Anirban Anirban - 14 days ago 7
Javascript Question

Scroll and run a code when section is visible ( pure Javascript )



function animateValue(id, start, end, duration) {
var range = end - start;
var current = start;
var increment = end > start? 1 : -1;
var stepTime = Math.abs(Math.floor(duration / range));
var obj = document.getElementById(id);
var timer = setInterval(function() {
current += increment;
obj.innerHTML = current;
if (current == end) {
clearInterval(timer);
}
}, stepTime);
}
animateValue("num1", 0, 75, 10000);

var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;

if(scrollTop > 400){
animateValue("num2", 0, 75, 10000);
}

.box{
height:500px;
}

<h1 id="num1">75</h1>
<div class="box"></div>
<h1 id="num2">75</h1>





I need to run the number from 0 to 75 on id="num2", like id="num1" is working. But I need id="num2" running after page is scrolled down there. And its a challenge because I can't use any library like Jquery, angular JS etc. I need it using pure JavaScript.

Answer

I added some events for scrolling and resizing (both can "show" the target element). We don't need the scrolling position when using .getBoundingClientRect(), because it shows us the targets top position depending on the scroll position.

https://jsfiddle.net/q8ww67tj/

function animateValue(id, start, end, duration) {
	var range = end - start;
	var current = start;
	var increment = end > start? 1 : -1;
	var stepTime = Math.abs(Math.floor(duration / range));
	var obj = document.getElementById(id);
	var timer = setInterval(function() {
		current += increment;
		obj.innerHTML = current;
		if (current == end) {
			clearInterval(timer);
		}
	}, stepTime);
}
animateValue("num1", 0, 75, 10000);

triggered = false;
window.addEventListener('load', recalculate);
window.addEventListener('scroll', recalculate);
window.addEventListener('resize', recalculate);

function recalculate() {
	var height = document.body.clientHeight,
		targetRect = document.getElementById('num2').getBoundingClientRect();
		targetY = targetRect['top'],
		targetHeight = targetRect['height'];
	
	if (targetY + targetHeight < height) {
		if (!triggered) {
			triggered = true;
			animateValue("num2", 0, 75, 10000);
		}
	}
}
.box {
  height: 1000px;
}
<h1 id="num1">75</h1>
<div class="box"></div>
<h1 id="num2">75</h1>