Previously, I used this approach for the target element and not the wrapper. However, it seems to be ineffective in this specific example. Upon running the code, some strange behaviors become apparent. The offsetTops of the sections are at 0 even before the wrappers are added to them. Another peculiar observation is that the wrappers seem to reach the very bottom, indicated by their offsetTops being calculated as body's offsetHeight minus the wrapper's offsetHeight. Could the issue be related to calling the function inside window.onload? I am puzzled as to what may be causing this. In each instance of logging to the console, the closest relatively positioned parent element appears to be the body. All elements have a display other than none. Can someone kindly shed light on what exactly is happening here? Also, please refrain from suggesting the use of getBoundingClientRect() as it does not apply in this context.
window.onload = function () {
const sections = document.querySelectorAll("section");
let eT = [];
for (let i = 0, len = sections.length; i < len; i++) {
const el = sections[i];
console.log(el.offsetTop, el.offsetParent);
if (el.parentNode.className !== "wrapper") {
const wrapper = document.createElement("div");
wrapper.className = "wrapper";
el.parentNode.appendChild(wrapper);
wrapper.appendChild(el);
wrapper.style.height = el.offsetHeight + "px";
wrapper.style.position = "relative";
}
const elCont = document.querySelectorAll(".wrapper")[i];
let elClone = elCont;
eT[i] = 0;
do {
eT[i] += elClone.offsetTop;
elClone = elClone.offsetParent;
}
while (elClone !== document.body);
console.log(eT[i], elCont.offsetHeight, document.body.offsetHeight);
}
}
section{
width: 100vw;
height: 1000px;
position: relative;
border: 1px solid;
}
body{
position: relative;
}
<body>
<section></section>
<section></section>
<section></section>
<section></section>
</body>
UPDATE I attempted using onscroll and everything functioned correctly. However, the underlying reasons for these anomalies remain unclear.
The load event occurs at the conclusion of the document loading process. At this stage, all objects in the document are present in the DOM, and all images, scripts, links, and sub-frames have completed loading. link
Hence, the behavior remains perplexing. Previously, I had also employed this function on load, where it worked without issues. Adding wrappers to the elements and retrieving their offsetTops seemed to trigger these unexpected occurrences. Furthermore, even when attempting the same process without wrappers, it failed to work. There were no alterations made to my previous working code, except for the introduction of the wrappers concept.