...

View Full Version : determining image's x and y coordinates within a page



DoubleV
01-13-2004, 07:21 PM
I would like to determine the absolute coordinates, not in relation to parent element. Tried searching this board, but didn't find what I was looking for. If this had already been answered, please direct me to the appropriate thread.

I tried implementing a script from this page (http://www.webreference.com/dhtml/diner/realpos1/7.html) and another one from this page (http://dbforums.com/arch/195/2003/9/918423) , but I get back coordinates that are 0,0 when I know my image is not positioned in the top left corner of a screen.

SlySecretSpy
01-13-2004, 07:24 PM
The problem is, if you don't set them, you can't get them. The variable of top and left is null if you just load the page with relative positioning.

A1ien51
01-13-2004, 07:30 PM
ACTUALLY You can figure out the position of the image or anything else on the page with a little coding......



<html>
<head>
<script>
var ErrorGapX = 0;
var ErrorGapY = 20;

function ErrorPosition(ErrorElement){
ErrorPosX = ErrorElement.offsetLeft
ErrorPosY = ErrorElement.offsetTop;
ErrorWidth = ErrorElement.clientWidth;
if(!ErrorWidth){ErrorWidth = ErrorElement.offsetWidth;}
//ErrorElement.value=ErrorWidth;
TheElement = ErrorElement.offsetParent;
while(TheElement != null){
ErrorPosX += TheElement.offsetLeft
ErrorPosY += TheElement.offsetTop;
TheElement = TheElement.offsetParent;
}
ErrorPosX += ErrorGapX;
ErrorPosY += ErrorGapY;

alert("(" + ErrorPosX + "," + ErrorPosY + ")");
}
</script>
</head>
<body>
<input type="button" name="ralph" onclick="ErrorPosition(this)" value="Click Me">
<img src="frogpic.jpg" onclick="ErrorPosition(this)">

</body>
</html>


Eric

DoubleV
01-13-2004, 08:44 PM
Alien,

does it only work onclick? I need it to work without having to click on the element, but when I tried it without the click it didn't work.

DoubleV
01-13-2004, 09:00 PM
I finally got it.
I put my javascript after the image in my code, but it was immideately after, so it looks like the image wasn't fully loaded yet when the script was called. I moved the script to the very bottom of the page and now it works.

thanks!

glenngv
01-14-2004, 04:18 AM
It's better to call the function onload of the image

<img src="frogpic.jpg" onload="ErrorPosition(this)">



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum