TypeError: Cannot read property 'offsetParent' of null when navigatin to another page

Clash Royale CLAN TAG#URR8PPP
TypeError: Cannot read property 'offsetParent' of null when navigatin to another page
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 becomes null. If that's the case how can i fix it?
obj
var bar = document.getElementById('nav');
put your js after the html part
– Edwin
Aug 8 at 11:41
this is reactjs.
– CraZyDroiD
Aug 8 at 11:43
1 Answer
1
Try to change
if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent)
to
if (obj && obj.offsetParent)
where should i use this?
– CraZyDroiD
Aug 8 at 11:52
but after you will change that - you'll get an error in this line else if (obj.y), so change it also to if (obj && obj.y)
– Sasha Kos
Aug 8 at 11:57
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
If you track back through the code, that means your line
var bar = document.getElementById('nav');is failing to find the element.– Utkanos
Aug 8 at 11:38