0

My knowledge of Javascript is exceptionally limited, so I would appreciate your assistance and patience with a very simple problem!

I have several spans with the same class. The spans contain numbers.

I want to trigger a count up animation when the span becomes visible to the user.

At the moment, the counters all begin to animate upon the page being loaded, which is not what I want.

MWE:

<html>
<body>
<div><span class="counter">200</span></div>
<div style="height:4000px;"></div>
<div><span class="counter">200</span></div>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/waypoints/2.0.3/waypoints.min.js"></script>
  <script src="https://cdn.jsdelivr.net/jquery.counterup/1.0/jquery.counterup.min.js"></script>

<script>
$('.counter').each(function () {
  $(this).prop('Counter', 0).animate({
    Counter: $(this).text() },
  {
    duration: 4000,
    easing: 'swing',
    step: function (now) {
      $(this).text(Math.ceil(now));
    } });

});
</script>


</body>

</html>
Craig
  • 105
  • 1
  • 4
  • 1
    Welcome to Stack Overflow! Visit the [help], take the [tour] to see what and [ask]. Please first ***>>>[Search for related topics on SO](https://www.google.com/search?q=jquery+counter+when+visible+site:stackoverflow.com)<<]`](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Mar 24 '21 at 12:32
  • "when the span becomes visible to the user"? how the span is visible to user? – Jai Gtz Mar 24 '21 at 12:53
  • I'm showing my ignorance of coding here, @JaiGtz. I mean when the number within the span becomes visible. So, a user scrolls down the page; the number comes into view and it starts counting. Then the user keeps scrolling; another number comes into view, and then it starts counting. Etc. The key point is that there are multiple counters, and I don't want them all to run at once. – Craig Mar 24 '21 at 12:59
  • https://stackoverflow.com/a/40658647/4988590, i think this will help you – Jai Gtz Mar 24 '21 at 13:08
  • Thanks @JaiGtz. Unfortunately I really have no idea what I am doing here, so while I don't doubt that this solution is correct, I really have no idea how to implement it into my example above. I tried wrapping that solution around my existing code, but with no luck. – Craig Mar 24 '21 at 13:46

0 Answers0