I have been working on a JavaScript function to create a counter effect for numbers when scrolled down. Unfortunately, it doesn't seem to be functioning properly and I am struggling to identify the issue. Here is a snippet of my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}">
<style>
.fake-div {
width:100%;
height: 1280px;
position:relative;
}
</style>
</head>
<body>
<div class="fake-div">
</div>
<div id="counter">
<div class="counter-value" data-count="300">0</div>
<div class="counter-value" data-count="400">100</div>
<div class="counter-value" data-count="1500">200</div>
</div>
<div class="fake-div">
</div>
<script>
var a = 0;
$(window).scroll(function() {
var oTop = $('#counter').offset().top - window.innerHeight;
if (a == 0 && $(window).scrollTop() > oTop) {
$('.counter-value').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({
countNum: $this.text()
}).animate({
countNum: countTo
},
{
duration: 2000,
easing: 'swing',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
//alert('finished');
}
});
});
a = 1;
}
});
</script>
</body>
</html>
Although I have used the same code from the following website, it does not seem to work on my desktop.
https://codepen.io/dmcreis/pen/VLLYPo
Your assistance in resolving this issue would be greatly appreciated. Please feel free to ask any questions below.