Forum Moderators: open

Message Too Old, No Replies

Find the position of a div element

         

MartinWeb

8:01 pm on Nov 21, 2009 (gmt 0)

10+ Year Member



I have a div element on a page that I cannot position absolutely. Does anyone know how to find it's X and Y value with JS? Thanks in advance.

Fotiman

3:01 pm on Nov 23, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



The Yahoo UI Library's DOM Utility [developer.yahoo.com] includes methods for getting the X and Y values.


<script type="text/javascript"
src="http://yui.yahooapis.com/2.8.0r4/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript">
var xy = YAHOO.util.Dom.getXY('myElement');
// xy is now an array with the x and y values
</script>

MartinWeb

8:04 pm on Nov 23, 2009 (gmt 0)

10+ Year Member



Great, Thanks!

MartinWeb

8:12 pm on Nov 23, 2009 (gmt 0)

10+ Year Member



Whenever I give it an id such as 10,20,30,40,50,etc. where the last digit is a zero, I get an error. When I do something like, 2, 11, or 23, it works fine. Why would this be?

[edited by: MartinWeb at 8:48 pm (utc) on Nov. 23, 2009]

Fotiman

8:37 pm on Nov 23, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Can you post your code example?

MartinWeb

8:49 pm on Nov 23, 2009 (gmt 0)

10+ Year Member



Sure.

var checking = 1;
while(checking<33){
var checkNow = new String (checking);
var here = document.getElementById(checkNow);
var check = new String (YAHOO.util.Dom.getXY(checkNow));
var checkArray=check.split(",");
checking++;
}

There is more code inside of the loop, but it is irrelevant.

Fotiman

9:55 pm on Nov 23, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Well, for one thing, id values can not start with a number. They must start with a letter [w3.org].
Also, in many circles it's considered bad practice to use "new" to create Typed Wrappers such as new String.

I would start by fixing your id values. Even if you just add a single letter before the number, so "1", "2", "3", ..., might become "i1", "i2", "i3",...

Next:
var checkNow = "i" + checking; // instead of new String

Next:
var check = YAHOO.util.Dom.getXY(checkNow);
// No need to convert to string, then back to array

MartinWeb

10:31 pm on Nov 23, 2009 (gmt 0)

10+ Year Member



Ok, thank you. It works now!