So I have a counter, and when I scroll to div, it should start counting, but it starts counting right as the whole page loads.
Html code of counters:
<section class="counters">
<div class="container2">
<div>
<i class="far fa-smile"></i>
<div class="counter" data-target="232">0</div>
<p>Happy Clients consequuntur quae</p>
</div>
<div>
<i class="fas fa-book"></i>
<div class="counter" data-target="521">0</div>
<p>Projects adipisci atque cum quia aut</p>
</div>
<div>
<i class="fas fa-headphones"></i>
<div class="counter" data-target="1463">0</div>
<p>Hours Of Support aut commodi quaerat</p>
</div>
<div>
<i class="fas fa-user-friends"></i>
<div class="counter" data-target="15">0 </div>
<p>Hard Workers rerum asperiores dolor</p>
</div>
</div>
</section>
Code of the function:
$('.counters counters2').waypoint(function() {
const counters = document.querySelectorAll('.counter');
const speed = 50; // The lower the slower
counters.forEach(counter => {
const updateCount = () => {
const target = +counter.getAttribute('data-target');
const count = +counter.innerText;
// Lower inc to slow and higher to slow
const inc = target / speed;
// console.log(inc);
// console.log(count);
// Check if target is reached
if (count < target) {
// Add inc to count and output in counter
counter.innerText = count + 3;
// Call function every ms
setTimeout(updateCount, 1);
} else {
counter.innerText = target;
}
};
updateCount();
});
});
}
So I used waypoint from jquery to activate the function when I scroll to div, but for some reason, the function activates when the page is loaded, without scrolling to the specific div.
Here is a simple example using onscroll
and offsetTop
.
<!DOCTYPE html>
<html>
<head>
<style>
#myDiv{
margin-top:1600px;
}
</style>
</head>
<body style="height:1500px">
<div id="myDiv" >
<p>Scroll down to this div</p>
</div>
<script>
window.onscroll = function() {myFunction()};
function myFunction() {
var testDivFromTop = document.getElementById("myDiv").offsetTop;
var pageHeight = window.innerHeight;
if (document.body.scrollTop > testDivFromTop - pageHeight || document.documentElement.scrollTop > testDivFromTop - pageHeight ) {
alert(1);
}
}
</script>
</body>
</html>
The way I would do it was simply use onscroll event . see the link https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onscroll