To determine the position of an element on a webpage, you can utilize the getBoundingClientRect method and calculate values based on the DOMRect.
This feature is widely supported across various browsers according to browser support data.
When working with a Reactjs
component, it's recommended to use a ref for direct access to the div in the physical DOM.
import React from 'react';
const Foobar = () => {
const onRef = (element) => {
const domRect = element.getBoundingClientRect();
console.log(`
Distance before top overflow: ${domRect.y}px
Distance before left overflow: ${domRect.x}px
Distance before right overflow: ${window.screen.width - domRect.right}px
Distance before bottom overflow: ${window.screen.height - domRect.bottom}px
`);
};
return (
<div ref={onRef}>
{# ... #}
</div>
);
}
export default Foobar;