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

I currently get a jQuery error that is driving me crazy."Cannot read properties of undefined (rea

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745398318a4625982.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信