I am trying to reposition an absolute
ly positioned element. If it appears partially or fully beyond the viewpoint then I want to reposition it to appear within the viewpoint. For that, I am trying to get the data using getBoundingClientRect()
to know its position and checking the DOMRect
bottom value against value of window.innerHeight
.
Also, the absolute
element’s parent is not positioned as relative
also nothing in the hierarchy.
If I do,
let pos = el.getBoundingClientRect();
if (window.innerHeight < pos['bottom']) {
style = `botton:${window.innerHeight}`; // set this to the style property of the element.
}
The above does not work and the absolute
ly positioned element appears in undesired location or does not appear at all. But meanwhile what I have noticed that there are some difference in values that I have got from getBoundingClientRect()
and the values displayed in Chrome’s DevTools -> Elements -> Computed.
So for test, if I use values from the Chrome’s Computed window and try to set those values in the DevTools: left: 1047.3px
– value from the Chrome; it appears exactly where it was positioned originally but when I try left: pos['left']
it displaces the element from its original position.
DOMRect:
{
'bottom': 377.68751525878906,
'height': 159.1354217529297,
'left': 1075.3333740234375,
'right': 1231.3333740234375,
'top': 218.55209350585938,
'width': 156,
'x': 1075.3333740234375,
'y': 218.55209350585938,
}
After all, I did not get why those values are different and how to calculate the values to position it within the viewpoint if it goes beyond the bottom edge of the screen.