Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to calculate offsetRight in javascript

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;    
}
like image 658
Dan Bailiff Avatar asked Jun 08 '10 20:06

Dan Bailiff


Video Answer


2 Answers

Cannot be more simpler than this:

let offsetright = window.innerWidth - obj.offsetLeft - obj.offsetWidth
like image 97
Siddhartha Mahato Avatar answered Nov 13 '22 20:11

Siddhartha Mahato


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';
like image 20
Modular Avatar answered Nov 13 '22 19:11

Modular