CMS Load + custom script only works on "page 1"

Hello there!
I’m using a custom script to format numbers in a CMS list with thousand separators. It works perfectly on the first page, but not on page two and thereafter. Any idea why?

The custom script is below.

The page is here.

Thankful for any ideas!
Jacob

<script>
  document.addEventListener("DOMContentLoaded", function () {
    // Define the separator function
    function formatNumberWithSeparator(number, separator) {
      return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, separator);
    }

    // Select all elements with the custom data attribute
    const elements = document.querySelectorAll("[data-format-number]");

    // Loop through the elements and format the numbers
    elements.forEach((el) => {
      const separator = el.getAttribute("data-separator") || " "; // Default to space
      const rawNumber = el.textContent.trim();

      // Parse and format the number
      if (!isNaN(rawNumber) && rawNumber !== "") {
        el.textContent = formatNumberWithSeparator(Number(rawNumber), separator);
      }
    });
  });
</script>```

hey @Jacob_B! This is due to how Webflow runs custom code, since the code is run on page load, only the items rendered on the page will be affected by your function.

The best practice when adding code is to use the CMS Load API that fires a renderitems event each time new items are loaded onto the page.

This is the basic structure of said callback function

<script>
  window.fsAttributes = window.fsAttributes || [];
  window.fsAttributes.push([
    'cmsload',
    (listInstances) => {
      console.log('cmsload Successfully loaded!');
  
      const [listInstance] = listInstances; // Only selects the first instance of CMS Load.

      // add your function here


     // call your function here for the first page items
  
      listInstance.on('renderitems', (renderedItems) => {
        console.log(renderedItems);
        // call your function here for newly rendered items
      });
    },
  ]);
</script>

Let me know if you need any help!