• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 277
  • 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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

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