Home > Mobile >  Cannot read properties of undefined (reading 'top') happens on every page except homepage
Cannot read properties of undefined (reading 'top') happens on every page except homepage

Time:02-10

I currently get a jQuery error that is driving me crazy.

"Cannot read properties of undefined (reading 'top')"

I implemented a simple scroll to anchor function.

    $('html,body').animate({
        scrollTop: $("#scroll").offset().top
      },
      'fast');
  });

Code is working fine on the homepage. But on all other pages it is returning the error below

"Cannot read properties of undefined (reading 'top')"

It is driving me crazy. All help is appreciated :)

CodePudding user response:

That's probably because the element that matches the #scroll selector does not exist on those pages that threw the error. When that happens, $('#scroll').offset() returned undefined, and you cannot access top from undefined.

To fix this, you will probably need to ensure the element exists before attempting to invoke the logic:

const $scroll = $('#scroll');

if ($scroll.length) {
    $('html,body').animate({
        scrollTop: $scroll.offset().top
    }, 'fast');
}
  • Related