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');
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745398318a4625982.html
评论列表(0条)