How to change Navmenu’s text color while scrolling?

I’m developing a website on Webflow and the fixed Navmenu should change the font color (black or white) according to the section’s background (light or dark). I’m using a custom JS code:

<script>
  /* Changing Colors and Logo by Section */
  function checkSectionTheme() {
    var pos = $(window).scrollTop();

    $('.theme-white, .theme-dark').each(function () {
      var pos_top = $(this).offset().top; // Use offset() for more accuracy
      var pos_bottom = pos_top + $(this).outerHeight();
      var class_name = $(this).hasClass("theme-white") ? "white" : "color";

      // Debugging positions
      console.log({
        currentScroll: pos,
        sectionTop: pos_top,
        sectionBottom: pos_bottom,
        sectionClass: class_name
      });

      if (pos >= pos_top && pos < pos_bottom) {
        if (class_name === "white") {
          $("body").removeClass("color").addClass("white");
        } else {
          $("body").removeClass("white").addClass("color");
        }
      }
    });
  }

  // Run function on page load and scroll
  $(document).ready(function () {
    checkSectionTheme();
    $(window).on("scroll", checkSectionTheme);
  });
</script>

It is partially working: the theme-dark (should have black font) only gets it right when we stop scrolling. While we scroll the font gets white like the theme-white sections. For the theme-white sections it works perfectly.

What am I missing here?

The first time I tried this exact code it was working perfectly. I’m assuming it stopped working correctly because I added a lot of content into this same section (to stick with the same seamless background), but the JS code should recalculate the height.