1

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.

MaxWidth
  • 468
  • 3
  • 9
  • You could take a look at this question on [How to wait until an element exists in the DOM](https://stackoverflow.com/questions/5525071/how-to-wait-until-an-element-exists) – Olian04 Sep 25 '17 at 09:14
  • I think if you use a hash instead of `?section=`, then the scrolling is automatically done for you by the browser. For example, if you have a link pointing to http://your.page/whatever#description, it will automatically scroll to element with id=description whenever such element becomes available. – guitarino Sep 25 '17 at 10:07
  • Alternatively, there is a very hacky solution that you can use... The problem is to detect when an element becomes visible in the page. The solution is to add a CSS style that would add a useless animation to the element whose visibility you want to detect. The animation can just do nothing (e.g. go from opacity 1 to 1). The benefit is that you can add an event listener to animationstart event on that element. So, when element becomes visible, it causes a useless animation to play, which causes an animationstart event, which triggers your listener, in which you can scroll to that element. – guitarino Sep 25 '17 at 10:19

0 Answers0