[Solved] How to solve the error ” Can not read property ‘top’ of null “?


  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>

solved How to solve the error ” Can not read property ‘top’ of null “?