How to Determine the Coordinates of an Element in JavaScript?
- 1). Open a new file in the text editor and save it as "coordinates.HTML." Write or copy this HTML document declaration code into the file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"> - 2). Write or copy this HTML <head> code into the file:
<head>
<title>Element Coordinates.</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<style type="text/css">
#box
{
position: absolute;
z-index: 1;
visibility: visible;
width: 10.0em;
height: 5.0em;
top: 1.0em;
left: 1.0em;
border : 2px solid #ccc;
-moz-border-radius: 0.5em;
-webkit-border-radius: 0.5em;
text-align:center;
padding : 1.0em;
}
p{
font-size: 1.2em;
font-weight: 900;
color : #000000;
}
</style>
<script type="text/javascript">
var x;
var y;
function getCoordinates()
{
x = Math.floor(Math.random()*40);
y = Math.floor(Math.random()*30);
document.getElementById("box").style.left = x + "em";
document.getElementById("box").style.top = y + "em";
x = document.getElementById("box").style.left;
y = document.getElementById("box").style.top;
alert ( "left = " + x );
alert ( "top = " + y );
}
</script>
</head> - 3). Write or copy this HTML <body> code into the file:
<body>
<div onmouseover="getCoordinates()">
<p>
Touch me!
</p>
</div>
</body>
</html> - 4). Save the file and open it in the web browser. Touch the element and it will move to a new position within the browser window and display the 'left' and 'top' coordinate values.
Source...