0

I am using Javascript with a little example like

<script>
  $(window).scroll(function () {
    if ($("#aboutUs").offset().top > 100) {
      $("#aboutUs").addClass("visible");
    } else {
      $("#aboutUs").removeClass("visible");
    }
  });
</script>

I have two pages on my project and a navigation bar to navigate each page. It shows an error like:

core.js:15723 ERROR TypeError: Cannot read property 'top' of undefined   
  at <anonymous>:5:47
  at dispatch (jquery.min.js:2)
  at v.handle (jquery.min.js:2)
  at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
  at Object.onInvokeTask (core.js:17289)
  at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
  at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188)
  at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:496)
  at invokeTask (zone.js:1540)
  at globalZoneAwareCallback (zone.js:1566)

It shows an error like this when I navigate to them and the result doesn't work either. But when I refresh the page, It works fine. I know that it shows an error because the element doesn't exist on the page. But I do have that and it works after refreshing page. How to get rid of that error? Thanks.

Edric
  • 24,639
  • 13
  • 81
  • 91
Adam
  • 351
  • 1
  • 4
  • 15
  • 4
    Does this answer your question? [TypeError jQuery offset().top is undefined](https://stackoverflow.com/questions/21477560/typeerror-jquery-offset-top-is-undefined) – ShamPooSham Dec 16 '19 at 07:15
  • Could you post a small working example of this code? I think `jQuery` just isn't able to find the element with ID `#aboutUs`. – Titulum Dec 16 '19 at 07:17

1 Answers1

1
if ($("#aboutUs").length) {
  if ($("#aboutUs").offset().top > 100) {
    $("#aboutUs").addClass("visible");
  } else {
    $("#aboutUs").removeClass("visible");
  }
}

Maybe your jquery code is running before view is rendered and Its not able to find element with id "aboutUs". So first check for the element existence and then write your code

Titulum
  • 9,928
  • 11
  • 41
  • 79
  • Thanks, guys It working now. I am very new to all these. $(window).scroll(function () { if ($('#aboutUs').length) { if ($('#aboutUs').offset().top > 100) { $('#aboutUs').addClass("l-header-thin--visible"); } else { $('#aboutUs').removeClass("l-header-thin--visible"); } } }); – Adam Dec 16 '19 at 07:30