This is a jQuery snippet intended to change the active class on a navigation item based on the scroll position. Everything works fine when tested, but I continue getting the error below.
Error:
Uncaught TypeError: Cannot read properties of undefined (reading 'addClass')
document.addEventListener("scroll", onScroll);
function onScroll(event) {
let scrollPosition = $(document).scrollTop();
let current;
$("aside a").removeClass("clicked");
$("aside a").each(function () {
let currentLink = $(this);
let refElement = $(currentLink.attr("href"));
if ( refElement.position().top 380 <= scrollPosition ) {
current = $(this);
}
});
current.addClass("clicked");
}
CodePudding user response:
if ( refElement.position().top 380 <= scrollPosition ) {
When the condition is false, current is undefined hence the error. If it still works as expected then you probably want to move the current.addClass("clicked");
inside the if statement.