0

With Javascript in DOM, I can use getBoundingClientRect to get the coordinate of the element, but it is based on viewport. The height of address bar and title bar are not included as I want to get the coordinate based on current browser window.

Is there a reliable method for get coordinate of element based on current browser window?

I tried use window.outerHeight - (window.innerHeight * window.devicePixelRatio) as the height of address bar and title bar, but it seems unreliable like it will be incorrect if the download bar is showing up in the bottom of the browser window.

Thomson
  • 20,586
  • 28
  • 90
  • 134

1 Answers1

0

You can calculate the page offset on a mouse event and then get your browser window offset. Doesn't work inside an iframe, we need access a iframe from the parent window, some solutions here: getBoundingClientRect from within iFrame

enter image description here

const pageOffset = {};
// you can collect the page offset on mouse move too
document.addEventListener('mousemove', async e => {
    pageOffset.x = e.screenX - e.pageX;
    pageOffset.y = e.screenY - e.pageY;
});

const $button = document.querySelector('button');

$button.addEventListener('click', e => {

    pageOffset.x = e.screenX - e.pageX;
    pageOffset.y = e.screenY - e.pageY;

    const rect = $button.getBoundingClientRect();
    alert(['x:', pageOffset.x - window.screenLeft + rect.left, 'y:', pageOffset.y - window.screenTop + rect.top].join(' '));
});
Alexander Nenashev
  • 8,775
  • 2
  • 6
  • 17