Home javascript Uncaught TypeError: Cannot read property 'top' of undefined how to fix it?

Uncaught TypeError: Cannot read property ‘top’ of undefined how to fix it?

Author

Date

Category

The script changes the navigation class when scrolling through sections on the page.

var menu_selector = ".sticky-tabs";
  function onScroll () {
    var scroll_top = $ (document) .scrollTop ();
    $ (menu_selector + "a"). each (function () {
      var hash = $ (this) .attr ("href");
      var target = $ (hash);
      if (target.position (). top & lt; = scroll_top & amp; & amp; target.position (). top + target.outerHeight () & gt; scroll_top) {
        $ (menu_selector + "a.active"). removeClass ("active");
        $ (this) .addClass ("active");
      } else {
        $ (this) .removeClass ("active");
      }
    });
  }
  $ (document) .ready (function () {
    $ (document) .on ("scroll", onScroll);
    $ ("a [href ^ = #]"). click (function (e) {
      e.preventDefault ();
      $ (document) .off ("scroll");
      $ (menu_selector + "a.active"). removeClass ("active");
      $ (this) .addClass ("active");
      var hash = $ (this) .attr ("href");
      var target = $ (hash);
      $ ("html, body"). animate ({
        scrollTop: target.offset (). top
      }, 500, function () {
        window.location.hash = hash;
        $ (document) .on ("scroll", onScroll);
      });
    });
  }); 

Answer 1, authority 100%

In this case, target.position () – returns undefined, which is possible only if target did not find any elements that match the selector.

In addition, depending on the version of jQuery, when using this method, null may also be returned, hence the error may change to

Uncaught TypeError: Cannot read property 'top' of null (...)

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions