Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the position of a div/span tag

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/spans on a page that I cannot specify the top/left properties for, but I need to display a div directly under that element.

like image 667
schmoopy Avatar asked Nov 13 '08 23:11

schmoopy


People also ask

How do I find the location of a div?

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').

How do you find the position element?

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.

How do I get the top position of a div?

offset(). top; This will give you the computed offset (relative to document) of any object.

How do you get the position element XY?

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.


2 Answers

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; 
like image 119
alex Avatar answered Sep 21 '22 12:09

alex


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; 
like image 22
nickf Avatar answered Sep 22 '22 12:09

nickf