getboundingclientrect not return same value

262 views Asked by At

Im tracking clicks on my website. For each clicks im taking the coordinates of the click on the clicked element ( referenced with the function getPath who return the css path) with the following function:

add_click(event) {
      var element = event.target;
      var dimensions = element.getBoundingClientRect();
      var click = {
        width: window.innerWidth,
        height: window.innerHeight,
        path: getPath(element),
        x: event.offsetX / dimensions.width,
        y: event.offsetY / dimensions.height,
        key: event.which
      };
      this.clicks.push(click);
    }

Then i'm creating visualisation of clicks. For this im reconverting X and Y coordinates of the element into X and Y coordinates of the window. For this im using :

var element = document.querySelector(path); //return the clicked element
var rect = element.getBoundingClientRect();
var X = rect.left + click["x"] * rect.width;
 var Y = rect.top + click["y"] * rect.height;

However getBoundingClientRect() is not returning the same value for an element every time i load page. Value returned from getBoundingClientRect() for a same element keep changing and this creating wrong coordinates for my click.

I have tested it on Chrome 87 and Firefox 78 both are returning different value for getBoundingClientRect() for the same exact window size.

Does anyone know why this is happening, have met this bug before or have another function that is not broken to get coordinates of a DOM element?

0

There are 0 answers