Can someone show me how to get the top
& left
position of a div
or span
element when one is not specified?
ie:
<span id='11a' style='top:55px;' onmouseover="GetPos(this);">stuff</span> <span id='12a' onmouseover="GetPos(this);">stuff</span>
In the above, if I do:
document.getElementById('11a').style.top
The value of 55px
is returned. However, if I try that for span
'12a', then nothing gets returned.
I have a bunch of div
/span
s on a page that I cannot specify the top
/left
properties for, but I need to display a div
directly under that element.
You can call the method getBoundingClientRect() on a reference to the element. Then you can examine the top , left , right and/or bottom properties... var offsets = document. getElementById('11a').
Use the Element. getBoundingClientRect() Function to Get the Position of an Element in JavaScript. The getBoundingClientRect() function produces a DOMRect object containing information about an element's size and position in the viewport.
offset(). top; This will give you the computed offset (relative to document) of any object.
The position of (X, Y) means the co-ordinate of an element at the top-left point in a document. X represent the horizontal position and Y represent the vertical position. Use element. getBoundingClientRect() property to get the position of an element.
You can call the method getBoundingClientRect()
on a reference to the element. Then you can examine the top
, left
, right
and/or bottom
properties...
var offsets = document.getElementById('11a').getBoundingClientRect(); var top = offsets.top; var left = offsets.left;
If using jQuery, you can use the more succinct code...
var offsets = $('#11a').offset(); var top = offsets.top; var left = offsets.left;
This function will tell you the x,y position of the element relative to the page. Basically you have to loop up through all the element's parents and add their offsets together.
function getPos(el) { // yay readability for (var lx=0, ly=0; el != null; lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent); return {x: lx,y: ly}; }
However, if you just wanted the x,y position of the element relative to its container, then all you need is:
var x = el.offsetLeft, y = el.offsetTop;
To put an element directly below this one, you'll also need to know its height. This is stored in the offsetHeight/offsetWidth property.
var yPositionOfNewElement = el.offsetTop + el.offsetHeight + someMargin;
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