PDA

View Full Version : Detecting Relative Positions in Javascript?



aaron1a12
06-02-2010, 10:58 PM
Hi guys, I'd like to any if anybody has any ideas on how to "Detecting Relative Positions in Javascript?"

I mean like having a main DIV and a secondary DIV and then detect the position of the secondary DIV relative to the main DIV. Something like "top-right", "bottom-left", "top", "bottom".

Then, is there a way to execute a specific action for each result? Like so:

if position = top-left, then execute top-left();
if position = bottom-right, then execute bottom-right();



Is this possible in JavaScript?

vwphillips
06-03-2010, 09:44 AM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title></title>
</head>

<body>
<div id="d1" >
Tom
<br />

<div id="d2" style=margin-Left:100px;" >****</div>
</div>
<script type="text/javascript">
/*<![CDATA[*/

function zxcPos(obj){
var rtn=[0,0];
while(obj){
rtn[0]+=obj.offsetLeft;
rtn[1]+=obj.offsetTop;
obj=obj.offsetParent;
}
return rtn;
}

var d1pos=zxcPos(document.getElementById('d1'));
var d2pos=zxcPos(document.getElementById('d2'));

alert('left: '+(d2pos[0]-d1pos[0])+'\ntop: '+(d2pos[1]-d1pos[1]))
/*]]>*/
</script>
</body>

</html>