I need to calculate the offsetRight of a DOM object. I already have some rather simple code for getting the offsetLeft, but there is no javascript offsetRight property. If I add the offsetLeft and offsetWidth, will that work? Or is there a better way?
function getOffsetLeft(obj)
{
if(obj == null)
return 0;
var offsetLeft = 0;
var tmp = obj;
while(tmp != null)
{
offsetLeft += tmp.offsetLeft;
tmp = tmp.offsetParent;
}
return offsetLeft;
}
function getOffsetRight(obj)
{
if (obj == null)
return 0;
var offsetRight = 0;
var tmp = obj;
while (tmp != null)
{
offsetRight += tmp.offsetLeft + tmp.offsetWidth;
tmp = tmp.offsetParent;
}
return offsetRight;
}
Cannot be more simpler than this:
let offsetright = window.innerWidth - obj.offsetLeft - obj.offsetWidth
A few choices:
1) If you want "offsetRight" relative to the viewport, use element.getBoundingClientRect().right;
2) Your example is good simply subracting the parent width from the element's width + offsetLeft.
3) Lastly, to be relative to the document, and to speed up traversing (offsetParent):
In this example, I'm positioning a pseudo dropdown element below the referenced element, but because I'm avoiding some tricky z-index issues and want to have the element be referenced from the right and expand out left, I had to append it to the body element, and the get the "offsetRight" from the original parent.
...
// Set helper defaults
dropdownElem.style.left = 'auto';
dropdownElem.style.zIndex = '10';
// Get the elem and its offsetParent
let elem = dropdownElemContainer;
let elemOffsetParent = elem.offsetParent;
// Cache widths
let elemWidth = elem.offsetWidth;
let elemOffsetParentWidth = 0;
// Set the initial offsets
let top = elem.offsetHeight; // Because I want to visually append the elem at the bottom of the referenced bottom
let right = 0;
// Loop up the DOM getting the offsetParent elements so you don't have to traverse the entire ancestor tree
while (elemOffsetParent) {
top += elem.offsetTop;
elemOffsetParentWidth = elemOffsetParent.offsetWidth;
right += elemOffsetParentWidth - (elem.offsetLeft + elemWidth); // Most important line like your own example
// Move up the DOM
elem = elemOffsetParent;
elemOffsetParent = elemOffsetParent.offsetParent;
elemWidth = elemOffsetParentWidth;
}
// Set the position and show the elem
dropdownElem.style.top = top + 'px';
dropdownElem.style.right = right + 'px';
dropdownElem.style.display = 'block';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With