Convert absolute position to relative - javascript

Is it possible to change DIV position from absolute to relative (and from relative to absolute)?
DIV should remain on same place.

Because formatting in comments is not work I will publish solution here
$(object).css({position: 'absolute',top: dy, left:dx});
// dy, dx - some coordinates
$(object).css({position: 'relative'});
Does not work: element position after changing to relative is different.
But when I stored offset and set it again after changing to relative, position is the same:
$(object).css({position: 'absolute',top: dy, left:dx});
var x = $(object).offset().left;
var y = $(object).offset().top;
$(object).css({position: 'relative'});
$(object).offset({ top: y, left: x });

you can change that attribute with
$(object).css({position: 'absolute'});
For instance:
You could use jQuery's methods .position() or .offset() to set "top" and "left"
css attribute aswell, that way your object should stay at it's position changing
from relative -> absolute.
I don't think that works vice versa.
demo code: http://jsbin.com/uvoka

If you really want to get the total top offset of an element that is a child of elements with absolute and relative positions you could use this function
function calcTotalOffsetTop(elm)
{
var totalOffsetTop = 0,
curr = elm;
while( curr.parent().is(':not(body)') )
{
curr = curr.parent();
totalOffsetTop += curr[0].offsetTop;
}
return totalOffsetTop;
}
this is the basically the code for the solution given by plodder above.

You can quite easily change it from relative to absolute by using it's offsetLeft and offsetTop values as left and top styles.
The other way around is harder. You would basically have to change it to relative and see where it ended up, then calculate new offset values from the current offset and the desired location.
Note that when the positioning is relative, the element is part of the page flow and may affect other elements. When the position is absolute, the element is outside the page flow and doesn't affect other elements. So, if you change between absolute and relative positioning, you may need to do changes to other elements also if you don't want them to move.

prototype.js has element.absolutize() and element.relativize which work very well.
The problem with going from relative to absolute is that
element.offsetTop and offsetLeft
only give the offset of your element to its parent.
You need to measure the cumualtive offset (i.e.
the offset of your element to its parent +
the offset of the parent to its parent +
the offset of its parent to its parent +
etc.)

Related

Difference between offsetParent and parentElement or parentNode

I have a following DOM structure
<body>
<div>
<table>
<outerElement>
<innerElement />
</outerElement>
<table>
</div>
</body>
DIV has its overflow set to auto so if table grows bigger - it scrolls within the DIV.
In this scenario why table.offsetParent returns the body while both table.parentNode and parentElement return the Div?
I need to calculate current position of the innerElement within the window, so I traverse from it up thru all parent elements, collecting their offsetTop and offsetLeft values. Up until the DIV offsetParent works fine and then it skips it directly to the body. The problem if there's scrolling involved at some point, I need to account for scrollTop and scrollLeft as well - like in the DIV in the above example. The problem is if I use offsetParent I never encounter the DIV as one of the parents.
UPDATE
This is part of the code that does the traversing:
while (oElem && getStyle(oElem, 'position') != 'absolute' && getStyle(oElem, 'position') != 'relative') {
curleft += oElem.offsetLeft;
curtop += oElem.offsetTop;
oElem = oElem.offsetParent;
}
where getStyle is a custom function that in this case retrieves the position style.
offsetParent is the closest parent that has position:relative or position:absolute or the body of the page. parentNode is the direct parent, regardless of position.
Using getBoudingClientRect() is really a great help (thanks Ally for the hint!).
If you still need the position relative to the upper left corner of the document, here's a helpful snippet:
if (node.getBoundingClientRect) {
var rect = node.getBoundingClientRect();
var sx = -(window.scrollX ? window.scrollX : window.pageXOffset);
var sy = -(window.scrollY ? window.scrollY : window.pageYOffset);
return {
x: rect.left - sx,
y: rect.top - sy
}
}
Note: document.body.getBoundingClientRect() may return an unexpected value for topin Firefox under some circumstances. Therefore, the window scroll position is more robust.
For the client who do not yet support getBoundingClientRect(), we still must walk the offetParents and take care that every overflow: scroll (or auto) parent has position: relative.
Stay clear of offsetParent, you'll have to add lots of hacks and checks to ensure you get it right.
Try using getBoundingClientRect instead.
offsetParent is essentially the parent in UI
parentNode is actually the parent in DATA/HTML
offsetParent is included to deprecate traditional parentNode

Find all parent elements with absolute position

I'm writing some javascript code to move all absolutely positioned elements down 60 pixels (below a 60 pixel heigh div I'm displaying at the top of other pages on my proxy). Here's the code I have right now (mostly borrowed from another question on stackoverflow):
function getStyle(el, prop)
{
var doc = el.ownerDocument;
var view = doc.defaultView;
if (view && view.getComputedStyle)
{
return view.getComputedStyle(el, '')[prop];
}
return el.currentStyle[prop];
}
function runAfterLoad()
{
var all = document.getElementsByTagName('*');
var i = all.length;
while (i--)
{
var topOffset = parseInt(all[i].offsetTop, 10);
if (getStyle(all[i], 'position') === 'absolute')
{
all[i].style.top = isNaN(topOffset) ? '60px' : (topOffset + 60) + 'px';
}
}
}
Unfortunately this moves all absolute positioned elements down 60 pixels. As it turns out, I found out that absolute positioning isn't actually absolute to the browser window, but absolute to a parent that meets some specific rules. Here's a quote from another answer on here:
This works because "position: absolute" means something like "use top, right, bottom, left" to position yourself in relation to the nearest ancestor who has "position: absolute" or "position: relative"."
So I'm looking for help on how to adjust my current code to only find the elements with absolute position that don't have a parent that is also absolute or relative positioned. Any help is highly appreciated.
Another option would be to use that fact to your advantage. If you were to wrap your entire page in a div which you positioned absolutely (or relatively) with top: 60px, you would essentially move the entire page down 60px at once.
This would also move non-absolute elements. If this is not desired then this won't work.

find element at an absolute position

How would you use jquery to get the element at a particular x, y coordinate? You can .offset and .position to find absolute and relative position using jquery.
Like this:
$(document.elementFromPoint(x, y))
Provided you know the exact coordinates relative to the document:
function getElsAt(top, left){return $("body").find("*").filter(function(){return $(this).offset().top == top && $(this).offset().left == left})}
The other answer stops at the first overlay.

How do I calculate the width between two elements?

I need to calculate the width between two elements but I'm not sure how I would go about this. Say I have the following:
<ul id="foo">
<li style="width:10px;">1</li>
<li style="width:20px;">2</li>
<li style="width:30px;">3</li>
</ul>
How would I calculate the distance between 1 and 3 (answer being 20px)? The width can be variable as can the number of list items? (I'm using the Prototype framework)
Thanks
If you mean the horizontal distance between two elements, you need the difference between the top right coord of the left element and the top left coord of the right element. The top right coord of an element is just the top left coord plus its width, as given in Pekka's answer.
To get the top left position an element, you can use the javascript method offsetLeft(). This returns the offset in the x dimension between an element and its parent. You iterate up the DOM tree adding successive offsetLeft's until you get to the document root. The resulting sum is your x position. The excellent Quirksmode shows you how to do this.
Edit: for completeness, I include example javascript to find an element's position:
function getNodePosition(node) {
var top = left = 0;
while (node) {
if (node.tagName) {
top = top + node.offsetTop;
left = left + node.offsetLeft;
node = node.offsetParent;
} else {
node = node.parentNode;
}
}
return [top, left];
}
If you mean the horizontal distance, I would say it's something like:
X position of element 2
minus
x position of element 1 plus width of element 1
to get the width, use getWidth()
to get the position, positionedOffset() might be the right thing, I'm not 100% sure and it depends on your elements' positioning.
And a general caveat, if your elements have padding, it will depend on the browser (IE / FF) whether the padding is calculated into the width or not. This may also apply to the border. You will have to play around and see.

height of an element javascript

I would like to adjust the size of an element in the opposite direction, so the code below does adjust it, but it enlarges it from current position to bottom, I want current position to top. What would be an efficient way of doing this? thanks
var ele=document.getElementById('mydiv');
ele.style.height = 500+'px';
Do what you're doing, then move the element up by its original height:
var ele=document.getElementById('mydiv');
ele.style.height = 500+'px';
ele.style.top -= 100+'px'; //or whatever the height originally was.

Categories

Resources