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 (...)