Updating counter from random number generator

Updating counter from random number generator

Project_ATLAS
Excursionist
30 0 3

Hey there,

I am trying to replicate something I saw on another Shopify site.

They have this really cool updating counter.

I've been able to replicate this fairly closely using the help of my robot butler (cough, ChatGPT), but it cannot fix any of the further issues with it.

I need it to load instantly, maybe I will need to give the JS it's own page that with an snippet inline to load it on the .liquid for this template or something IDK. I also am trying to have it fade in and out on both initial load, and on all subsequent refreshes.

Lastly, the tally should only update by a maximum of say 20 at any refresh, the actual number being random though.

Thank you in advance for any assistance.


Here is the current code I have:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Simulated Fluffy Clouds Count</title>
  <style>
    /* Inline CSS for basic styling */
    body {
      font-size: 10px;
      font-weight: 400;
    }

    .fade-in-out {
      animation: fadeInOut 1s ease-in-out; /* Fade-in and fade-out animation */
    }

    @keyframes fadeInOut {
      0% { opacity: 0; }
      100% { opacity: 1; }
    }

    .live-views {
      font-size: 10px;
      font-weight: 400;
      color: #333;
    }
  </style>
</head>
<body class="fade-in-out">
  <div>
    <p><span id="liveViewsCounter" class="live-views"></span> Fluffy clouds in the sky.</p>
  </div>

  <script>
    function updateLiveViews() {
      const liveViewsCounter = document.getElementById('liveViewsCounter');
      if (liveViewsCounter) {
        // Generate a random number between 15 and 88 (adjusted range)
        let newCount = Math.floor(Math.random() * (88 - 15 + 1)) + 15;

        // Ensure the number doesn't end in zero
        while (newCount % 10 === 0) {
          newCount = Math.floor(Math.random() * (88 - 15 + 1)) + 15;
        }

        // Determine the next count within 20 intervals (up or down)
        let increment = Math.floor(Math.random() * 2) === 0 ? -20 : 20;

        // Adjust the increment to ensure the count doesn't change more than 20
        while ((newCount + increment) % 10 === 0) {
          increment = Math.floor(Math.random() * 2) === 0 ? -20 : 20;
        }

        newCount += increment;

        liveViewsCounter.textContent = newCount;
      }
    }

    // Update views initially and set interval for updates (every 7 seconds)
    window.onload = function () {
      updateLiveViews(); // Update immediately on page load
      setInterval(updateLiveViews, 7000); // Update every 7 seconds
    };
  </script>
</body>
</html>
Replies 0 (0)