I'm using a code to stick a div on top when scrolling and the div reaches the top.
The code is working correctly but i'm getting a error when navigating to another page .
TypeError: Cannot read property 'offsetParent' of null
My code
render() {
var startProductBarPos = -1;
window.onscroll = function () {
var bar = document.getElementById('nav');
if (startProductBarPos < 0) startProductBarPos = findPosY(bar);
if (window.pageYOffset > startProductBarPos) {
bar.style.position = 'fixed';
bar.style.width = '58.6%'
bar.style.top = 0;
} else {
bar.style.position = 'relative';
bar.style.width = '100%'
}
};
function findPosY(obj) {
var curtop = 0;
if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent) {
while (obj.offsetParent) {
curtop += obj.offsetTop;
obj = obj.offsetParent;
}
curtop += obj.offsetTop;
} else if (obj.y)
curtop += obj.y;
return curtop;
};
return(
<div className="trait_type_header" id="nav">
</div>
);
}
This is line it's showing where the error is.
if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent) {
I think when navigating to another page obj
bees null. If that's the case how can i fix it?
I'm using a code to stick a div on top when scrolling and the div reaches the top.
The code is working correctly but i'm getting a error when navigating to another page .
TypeError: Cannot read property 'offsetParent' of null
My code
render() {
var startProductBarPos = -1;
window.onscroll = function () {
var bar = document.getElementById('nav');
if (startProductBarPos < 0) startProductBarPos = findPosY(bar);
if (window.pageYOffset > startProductBarPos) {
bar.style.position = 'fixed';
bar.style.width = '58.6%'
bar.style.top = 0;
} else {
bar.style.position = 'relative';
bar.style.width = '100%'
}
};
function findPosY(obj) {
var curtop = 0;
if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent) {
while (obj.offsetParent) {
curtop += obj.offsetTop;
obj = obj.offsetParent;
}
curtop += obj.offsetTop;
} else if (obj.y)
curtop += obj.y;
return curtop;
};
return(
<div className="trait_type_header" id="nav">
</div>
);
}
This is line it's showing where the error is.
if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent) {
I think when navigating to another page obj
bees null. If that's the case how can i fix it?
-
If you track back through the code, that means your line
var bar = document.getElementById('nav');
is failing to find the element. – Mitya Commented Aug 8, 2018 at 11:38 - put your js after the html part – Edwin Commented Aug 8, 2018 at 11:41
- this is reactjs. – CraZyDroiD Commented Aug 8, 2018 at 11:43
1 Answer
Reset to default 5Try to change
if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent)
to
if (obj && obj.offsetParent)