Search code examples
javascriptjqueryonscroll

How to solve the error " Can not read property 'top' of null "?


I am trying to make a function for scrolling event in HubSpot CMS, but getting the error for onScroll event.The script is as below:

Error I am getting on line: if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos)

TypeError: Cannot read property 'top' of null

var module_9519291 = (function() {
  var __hs_messages = {};
  i18n_getmessage = function() {
    return hs_i18n_getMessage(__hs_messages, hsVars['language'], arguments);
  };
  i18n_getlanguage = function() {
    return hsVars['language'];
  };
  $(document).ready(function() {
    $(document).on("scroll", onScroll);

    // Smooth scroll
    $('a[href^="#"]').on('click', function(e) {
      e.preventDefault();
      $(document).off("scroll");
      $('a').each(function() {
        $(this).removeClass('active');
      })
      $(this).addClass('active');

      var target = this.hash,
        menu = target;
      $target = $(target);
      $('html, body').stop().animate({
        'scrollTop': $target.offset().top + 2
      }, 300, 'swing', function() {
        window.location.hash = target;
        $(document).on("scroll", onScroll);
      });
    });
  });

  function onScroll(event) {
    var scrollPos = $(document).scrollTop();
    $('#myP a').each(function() {
      var currLink = $(this);
      var refElement = $(currLink.attr("href"));
      if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
        $('#myP ul li a').removeClass("active");
        currLink.addClass("active");
      } else {
        currLink.removeClass("active");
      }
    });
  }


  window.onscroll = function() {
    myFunction()
  };

  function myFunction() {
    if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 2000) {
      document.getElementById("myP").className = "flyout";
    } else {
      document.getElementById("myP").className = "";
    }
  }


  $(".b-toggler").click(function() {
    $("#myP").toggleClass("b-hidden");
  });





})();
<body ...>

<a name="top"></a>
<div class="parallax-mirror" style="visibility: hidden; z-index: -100; position: fixed; top: 0px; left: 0px; overflow: hidden; height: 400px; width: 736px; transform: translate3d(0px, -388.594px, 0px);"><img alt="parallax" class="parallax-slider" src="https://cdn2.hubspot.net/hubfs/5220222/Website/pillarpage/roboadvisor/robo-advisor-whitebox.jpg" style="position: absolute; height: 531px; width: 944px; max-width: none; transform: translate3d(-104px, 310.875px, 0px);"></div>  

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="hs_cos_wrapper_widget_1569937812303" class="hs_cos_wrapper hs_cos_wrapper_widget hs_cos_wrapper_type_module" style="" data-hs-cos-general-type="widget" data-hs-cos-type="module">
      <div id="" class="icons-top  bg-light  pt80 pb80 mt0 mb0">
        <div class="centered md-w800">
          <div class="">

            <div class="accordion-item soft content-counter clearfix">
              <div class="accordion-header">
                <div class="accordion-icon">
                  <div class="expand-icon text-small">
                    Inhaltsübersicht einblenden <span style="padding-left: 10px;" class="wb-icon whitebox-arrow-down-1"></span>
                  </div>
                  <div class="collapse-icon text-small">
                    Inhaltsübersicht ausblenden <span style="padding-left: 10px;" class="wb-icon whitebox-close"></span>
                  </div>
                </div>
                <h2 class="accordion-title">Inhaltsverzeichnis</h2>
              </div>
              <div class="accordion-body clearfix content-counter">
                <span id="hs_cos_wrapper_widget_1569937812303_" class="hs_cos_wrapper hs_cos_wrapper_widget hs_cos_wrapper_type_simple_menu" style="" data-hs-cos-general-type="widget" data-hs-cos-type="simple_menu"><div id="hs_menu_wrapper_widget_1569937812303_" class="hs-menu-wrapper active-branch flyouts hs-menu-flow-horizontal" role="navigation" data-sitemap-name="" data-menu-id="" aria-label="Navigation Menu">
         <ul>
          <li class="hs-menu-item hs-menu-depth-1"><a href="#welche-vorteile" role="menuitem" target="_self">Welche Vorteile versprechen Robo-Advisors ihren Kunden?</a></li>
          <li class="hs-menu-item hs-menu-depth-1"><a href="#wie-werde-ich" role="menuitem" target="_self">Wie werde ich Kunde bei einem Robo-Advisor?</a></li>
         
         </ul>
        </div></span>
              </div>
            </div>

          </div>
        </div>
      </div>

      <div id="myP" class="">
        <div class="content-counter"><span id="hs_cos_wrapper_widget_1569937812303_" class="hs_cos_wrapper hs_cos_wrapper_widget hs_cos_wrapper_type_simple_menu" style="" data-hs-cos-general-type="widget" data-hs-cos-type="simple_menu"><div id="hs_menu_wrapper_widget_1569937812303_" class="hs-menu-wrapper active-branch flyouts hs-menu-flow-horizontal" role="navigation" data-sitemap-name="" data-menu-id="" aria-label="Navigation Menu">
         <ul>
          <li class="hs-menu-item hs-menu-depth-1"><a href="#welche-vorteile" role="menuitem" target="_self">Welche Vorteile versprechen Robo-Advisors ihren Kunden?</a></li>
          <li class="hs-menu-item hs-menu-depth-1"><a href="#wie-werde-ich" role="menuitem" target="_self">Wie werde ich Kunde bei einem Robo-Advisor?</a></li>
          <li class="hs-menu-item hs-menu-depth-1"><a href="#benoetigt-ein-robo" role="menuitem" target="_self">Benötigt ein Robo-Advisor eine Erlaubnis der BaFin?</a></li>
          <li class="hs-menu-item hs-menu-depth-1"><a href="#ist-jeder-bafin" role="menuitem" target="_self">Ist jeder BaFin-regulierte Robo-Advisor ein echter Vermögensverwalter?</a></li>
          <li class="hs-menu-item hs-menu-depth-1"><a href="#was-bedeutet-es" role="menuitem" target="_self">Was bedeutet es, wenn ein Robo-Advisor „aktiv“ ist?</a></li>
          <li class="hs-menu-item hs-menu-depth-1"><a href="#wieso-ist-passiv" role="menuitem" target="_self">Wieso ist passiv gut, ganz passiv aber doch nicht?</a></li>
          <li class="hs-menu-item hs-menu-depth-1"><a href="#was-ist-denn" role="menuitem" target="_self">Was ist denn nun „robo“ am „Robo“? Erledigt nicht sowieso alles ein Algorithmus?</a></li>
          <li class="hs-menu-item hs-menu-depth-1"><a href="#ist-das-portfoliomanagement" role="menuitem" target="_self">Ist das Portfoliomanagement eines Robo-Advisors anders als das eines analogen Vermögensverwalters?</a></li>
          <li class="hs-menu-item hs-menu-depth-1"><a href="#schlaegt-die-stunde" role="menuitem" target="_self">Schlägt die Stunde der Wahrheit für Robos, wenn die Märkte unruhig sind?</a></li>
          <li class="hs-menu-item hs-menu-depth-1"><a href="#ist-die-maschine" role="menuitem" target="_self">Ist die Maschine besser als der Mensch?</a></li>
          <li class="hs-menu-item hs-menu-depth-1"><a href="#dann-ist-also" role="menuitem" target="_self">Dann ist also gar nicht alles „robo“ an einem „Robo“?</a></li>
          <li class="hs-menu-item hs-menu-depth-1"><a href="#wie-viel-vorwissen" role="menuitem" target="_self">Wie viel Vorwissen braucht ein Robo-Kunde? Für wen eignet sich ein Robo-Advisor? </a></li>
          <li class="hs-menu-item hs-menu-depth-1"><a href="#welcher-robo-advisor" role="menuitem" target="_self">Welcher Robo-Advisor ist der richtige für mich?</a></li>
          <li class="hs-menu-item hs-menu-depth-1"><a href="#wie-ueberpruefe-ich" role="menuitem" target="_self">Wie überprüfe ich die Leistung eines Robos? </a></li>
          <li class="hs-menu-item hs-menu-depth-1"><a href="#woher-kommen-die" role="menuitem" target="_self">Woher kommen die Robos und wie wird sich der Markt entwickeln?</a></li>
          <li class="hs-menu-item hs-menu-depth-1"><a href="#video-so-funktioniert" role="menuitem" target="_self">Video: So funktioniert Whitebox (3:03 min)</a></li>
         </ul>
        </div></span></div>
        <div style="padding-top: 30px;"><span style="padding:10px; color: #fff; font-size: 1.5em;" class="b-toggler bg-theme wb-icon whitebox-navigation-menu"></span></div>
      </div>

    </div>


Solution

    1. You do not HAVE anything in your HTML with id=welche-vorteile for example
    2. You need to show us where your navigation sits, because as you can see, even with Math.floor, you never get the values to match
    3. You also seem to do several things on scroll which you should do in one on("scroll") - if you have jQuery use it consistently

    $(document).ready(function() {
      $(document).on("scroll", onScroll);
    });
    
    function onScroll(event) {
      var scrollPos = Math.floor($(document).scrollTop());
      $('#myP a').each(function() {
        var $currLink = $(this),
          href = $currLink.attr("href"),
          $refElement = $(href);
        if ($refElement.length>0) {
          var top = Math.floor($refElement.position().top),
            height = Math.floor($refElement.height()),
            activate = top <= scrollPos && scrollPos < (top + height)
          $("#pos").text(top + "<=" + scrollPos + "&&" + scrollPos + "<" + (top + height))
          $(this).toggleClass("active", activate);
        }
        else {
          console.log("Nothing found in the page with id",href)
        }
      });
    }
    a {
      text-decoration: none
    }
    
    .active {
      text-decoration: underline: color: red
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="myP" class="" style="position:fixed">
      <div class="content-counter"><span id="hs_cos_wrapper_widget_1569937812303_" class="hs_cos_wrapper hs_cos_wrapper_widget hs_cos_wrapper_type_simple_menu" style="" data-hs-cos-general-type="widget" data-hs-cos-type="simple_menu"><div id="hs_menu_wrapper_widget_1569937812303_" class="hs-menu-wrapper active-branch flyouts hs-menu-flow-horizontal" role="navigation" data-sitemap-name="" data-menu-id="" aria-label="Navigation Menu">
         <ul>
          <li class="hs-menu-item hs-menu-depth-1"><a href="#welche-vorteile" role="menuitem" target="_self">Welche Vorteile versprechen Robo-Advisors ihren Kunden?</a></li>
          <li class="hs-menu-item hs-menu-depth-1"><a href="#wie-werde-ich" role="menuitem" target="_self">Wie werde ich Kunde bei einem Robo-Advisor?</a></li>
    
         </ul>
        </div></span></div>
      <div style="padding-top: 30px;"><span style="padding:10px; color: #fff; font-size: 1.5em;" class="b-toggler bg-theme wb-icon whitebox-navigation-menu"></span></div>
    </div>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <div id="welche-vorteile">Welche Vorteile <span id="pos"></span></div>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>
    <p>...</p>