I have a function where I take its parameters from an element via getBoundingClientRect.
I tried to look through window.pageXOffset if I added it, I also added setTimeout to no avail.
Edge browser and Chrome have different values for the same extension.
How can I correct this? or how to find the correct values for letft and top?
4
Here are some things to consider. I ran this in Chrome, Edge and FireFox on the same box
Using Math.round() for consistency gave a consistent result
const roundedLeft = Math.round(rect.left + window.pageXOffset);
const roundedTop = Math.round(rect.top + window.pageYOffset);
console.log(roundedLeft, roundedTop)
const element = document.getElementById('rect')
const rect = element.getBoundingClientRect();
// Scroll Offsets and absolute position relative to the document rather than the viewport
const absoluteLeft = rect.left + window.pageXOffset;
const absoluteTop = rect.top + window.pageYOffset;
console.log(absoluteLeft)
const scale = window.devicePixelRatio;
const scaledLeft = rect.left * scale;
const scaledTop = rect.top * scale;
console.log(scaledLeft)
console.log(scaledTop)
// Using Math.round() for consistency
const roundedLeft = Math.round(rect.left + window.pageXOffset);
const roundedTop = Math.round(rect.top + window.pageYOffset);
console.log(roundedLeft, roundedTop)
/*
Chrome in snippet editor Win 10
344.9928894042969
455.39063210926906
10.54687501855193
345 8
Edge on same device
345
414.00001645088196
9.593750190486503
345 8
Firefox, same device
345
414
9.6
345 8
*/
#rect {
background-color:red;
width: 512px;
height: 734px;
position: absolute;
top: 123;
left: 345px
}
<div id="rect"></div>