• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 273
  • Last Modified:

Can I get the coordination for one <td> in a table using Javascript?

I try to the coordination for one of <td> cells in a table such as Top and Left using Javascript. How to implement it? Thanks in advance!
0
zhao790
Asked:
zhao790
1 Solution
 
dakydCommented:
You meant coordinates of that cell, right?  Give the below function a shot, it takes in the object, and returns an array of coordinates (x,y):

function getPos(obj)
{
  var answer = new Array(0,0);
  var temp = obj;
  while (temp.offsetParent)
  {
    answer[0] += temp.offsetLeft;
    answer[1] += temp.offsetTop;
    if (obj.clientLeft && obj.tagName != "BODY")
    {
      answer[0] += temp.clientLeft;
      answer[1] += temp.clientTop;
    }
    temp = temp.offsetParent;
  }
  return answer;
}

So, for example:

<html>
<head>
<script type="text/javascript">
function getPos(obj)
{
  var answer = new Array(0,0);
  var temp = obj;
  while (temp.offsetParent)
  {
    answer[0] += temp.offsetTop;
    answer[1] += temp.offsetLeft;
    if (obj.clientLeft && obj.tagName != "BODY")
    {
      answer[0] += temp.clientTop;
      answer[1] += temp.clientLeft;
    }
    temp = temp.offsetParent;
  }
  return answer;
}
</script>
<style type="text/css">
body {
  margin: 0;
  padding: 0;
}

#myTbl {
  border-collapse: collapse;
}

#myTbl td {
  border: 1px solid black;
  width: 50px;
  height: 25px;
}
</style>
</head>

<body>
<table id="myTbl">
  <tr>
    <td>a</td>
    <td>1</td>
  </tr>
  <tr>
    <td>b</td>
    <td id="myCell">2</td>
  </tr>
</table>

<input type="button" onclick="alert(getPos(document.getElementById('myCell')).toString());"
  value="Get Position of Cell with '2' in it">
</body>

Hope that helps.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now