Run Counter Animation on Multiple Elements When in View

Hello, I am a complete Javascript novice, however I need to solve a Javascript problem and I have completely no idea how to do it. I suspect the answer is very simple!

I have the following code (the script is taken from here). I want the elements with the class countup to ‘count up’ as per the script when they are in view on a website.

Could you please provide me with some assistance? Thanks in advance!



<div><span class="countup">200</span></div>
<div><span class="countup">200</span></div>
<div style="height:4000px;"></div>
<div><span class="countup">200</span></div>

<script id="rendered-js" >
// How long you want the animation to take, in ms
const animationDuration = 2000;
// Calculate how long each ‘frame’ should last if we want to update the animation 60 times per second
const frameDuration = 1000 / 60;
// Use that to calculate how many frames we need to complete the animation
const totalFrames = Math.round(animationDuration / frameDuration);
// An ease-out function that slows the count as it progresses
const easeOutQuad = t => t * (2 - t);

// The animation function, which takes an Element
const animateCountUp = el => {
  let frame = 0;
  const countTo = parseInt(el.innerHTML, 10);
  // Start the animation running 60 times per second
  const counter = setInterval(() => {
    // Calculate our progress as a value between 0 and 1
    // Pass that value to our easing function to get our
    // progress on a curve
    const progress = easeOutQuad(frame / totalFrames);
    // Use the progress value to calculate the current count
    const currentCount = Math.round(countTo * progress);

    // If the current count has changed, update the element
    if (parseInt(el.innerHTML, 10) !== currentCount) {
      el.innerHTML = currentCount;

    // If we’ve reached our last frame, stop the animation
    if (frame === totalFrames) {
  }, frameDuration);

// Run the animation on all elements with a class of ‘countup’
const runAnimations = () => {
  const countupEls = document.querySelectorAll('.countup');
//# sourceURL=pen.js



What you’re looking for is called intersection observer. If you’re completely new to JavaScript. it’s probably difficult to understand it just by reading the docs, but there’s a lot of good tutorials on YouTube. You might have to watch a few.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.