I have several sections-elements on my page - each of them has an id
-value (e.g. id="description"
) and if that id
-value is present as parameter inside the URL (?section=description
) then it shall scroll to that section-element on the page.
Hereby, I am using the window.onload
function.
The problem is that the coordiantes (and width and height) of the section-elements on the page are determined too early before they are correct (before browser has displayed everything) and thus the scroll ends up at the wrong location.
E.g. wrong coords of section element with id="description"
when determined by window.onload
:
DOMRect { x: 665.2833251953125, y: 789.7666625976562, width:
602.433349609375, height: 296.4666748046875, top: 789.7666625976562, right:
1267.7166748046875, bottom: 1086.2333374023438, left: 665.2833251953125 }
E.g. correct coordnates when also using window.onload
but additionally waiting 2s with timeOut
function:
DOMRect { x: 538.2999877929688, y: 860.2000122070312, width:
856.4000244140625, height: 155.60000610351562, top: 860.2000122070312,
right: 1394.7000122070312, bottom: 1015.8000183105469, left:
538.2999877929688 }
using setTimeout can't be the solution. Is there a different way to tell when the element's coordnates can correctly be determined?
Thanks a lot for any hint.