admin管理员组文章数量:1426118
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
1 Answer
Reset to default 3That'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');
}
本文标签:
版权声明:本文标题:javascript - Cannot read properties of undefined (reading 'top') happens on every page except homepage - Stack O 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745398318a2656918.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论