How to Determine the Coordinates of an Element in JavaScript?
The screen coordinates of an element are specified in its style declaration and stored by the browser within the Document Object Model (DOM) of the displayed HTML page. Each element within the DOM is given an identity string (id). A JavaScript code can access a particular element with this identity string as a reference and can obtain the particular values for the 'left' and 'top' coordinates of the elements within the browser window.
Instructions
-
-
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 id="box" 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.
-
1