Home > Blockchain >  Why am I getting a console error on addClass, but everything still works as expected?
Why am I getting a console error on addClass, but everything still works as expected?

Time:10-15

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.

  • Related