最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot read properties of undefined (reading 'top') happens on every page except homepage - Stack O

programmeradmin1浏览0评论

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 :)

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 :)

Share Improve this question asked Feb 9, 2022 at 10:40 Leroy WubbelsLeroy Wubbels 891 silver badge11 bronze badges 1
  • are you sure you have #scroll element on your pages? – Georgy Commented Feb 9, 2022 at 10:45
Add a ment  | 

1 Answer 1

Reset to default 3

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');
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论