I made a script that moves my "character" (element ID="character") to where I click. But I need to get it's position so I can make it "walk" to where I click instead of it just appearing there.
This is my code:
<html>
<head>
<script type="text/javascript">
function showCoords(evt){
document.getElementById("character").style.left = evt.pageX;
document.getElementById("character").style.top = evt.pageY;
}
</script>
</head>
<body onmousedown="showCoords(event)">
<div id="character" style="position: absolute; top: 100px; width: 80px; height: 40px; background:black;"> Char </div>
</body>
</html>
Basically I just want to retrieve the element's horizontal and vertical position at the beginning of my function. So I can later use those variables. How do I do it?
Thanks
I made a script that moves my "character" (element ID="character") to where I click. But I need to get it's position so I can make it "walk" to where I click instead of it just appearing there.
This is my code:
<html>
<head>
<script type="text/javascript">
function showCoords(evt){
document.getElementById("character").style.left = evt.pageX;
document.getElementById("character").style.top = evt.pageY;
}
</script>
</head>
<body onmousedown="showCoords(event)">
<div id="character" style="position: absolute; top: 100px; width: 80px; height: 40px; background:black;"> Char </div>
</body>
</html>
Basically I just want to retrieve the element's horizontal and vertical position at the beginning of my function. So I can later use those variables. How do I do it?
Thanks
Share Improve this question edited May 3, 2011 at 2:39 lisovaccaro asked May 3, 2011 at 2:18 lisovaccarolisovaccaro 34.1k99 gold badges271 silver badges423 bronze badges 3-
I'm confused: does
document.getElementById("character").style.left
and.top
not give you those values to start with? – Gordon Seidoh Worley Commented May 3, 2011 at 2:23 -
It depends on the
position
property of that element. For example, if its value isrelative
, then theleft
andtop
properties (if ever defined) will tell you just how many pixels the element is relative to its parent. – Nicolás Ozimica Commented May 3, 2011 at 2:34 - I thought document.getElementById("character").style.left was only to change it's position. How can I print that value? That would answer my question. Thanks – lisovaccaro Commented May 3, 2011 at 2:37
2 Answers
Reset to default 6If you only need this to work in reasonably modern browsers, then document.getElementById("character").getBoundingClientRect()
will have left
and top
properties that give you the offsets from the viewport.
Using MooTools you can get the position of an element with:
$('element').getPosition(); // returns {x: 100, y: 500};
MooTools docs: Element Method: getPosition