Reputation: 3308
Below is an example of establishing a counter in html (sourced from internet).
JS
$(document).ready(function() {
var positionFromTop = 100;
$(window).scroll(function() {
var $y = $(window).scrollTop();
if ($y >= positionFromTop) {
var i;
for (i = 0; i <= 5400; i += 100) {
setTimeout(Counter_Fn(i), 3000);
}
}
});
});
function Counter_Fn(x) {
document.getElementById("Counter_1").innerHTML = x;
}
body {
background-color: #F46A6A;
color: #fff;
max-width: 800px;
margin: 1000px auto 0;
text-align: center;
display: table;
}
.counter {
display: table-cell;
margin: 1.5%;
font-size: 50px;
background-color: #FF6F6F;
width: 200px;
border-radius: 50%;
height: 200px;
vertical-align: middle;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id = "Counter_1" class="counter">0</div>
While this is serving basic purpose of mine, but I want to add few more details as below
Any pointer to achieve above functionalities will be highly appreciated
Upvotes: 0
Views: 379
Reputation: 17711
1) To run some code when user scrolls down to a certain point in page, you should put your code inside a function, and then, in the $(document).ready(), you should use:
$(document).ready(function() {
var positionFromTop = 1234; // for example
$(window).scroll(function() {
var $y = $(window).scrollTop();
if ($y >= position) {
callyourFunctionToCount();
}
});
}
2) To use a step different from 1 you can't use animate()
. You should use some sort of a timed counter, like it is well described here, for example.
https://stackoverflow.com/a/2540673/709439.
3) The same as for point 2: using a counter it becomes easy to set your increment value and the output format.
Upvotes: 1