Skip to content

Instantly share code, notes, and snippets.

@barryvan
Created March 14, 2012 07:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save barryvan/2034786 to your computer and use it in GitHub Desktop.
Save barryvan/2034786 to your computer and use it in GitHub Desktop.
Determining a table cell's x and y position/index
// See http://www.barryvan.com.au/2012/03/determining-a-table-cells-x-and-y-positionindex
Element.implement({
getCellCoords: function() {
if (this.get('tag') !== 'td' && this.get('tag') !== 'th') return null;
var result = {};
// The y-coord is simply the number of <tr> elements that precede our parent, plus our parent.
result.y = this.getParent('tr').getAllPrevious('tr').length;
/* The x-coord is a little more difficult. We can't simply count up the number of preceding cells:
+----------+-------------+
| (a) | (b) |
+ +------+------+
| | (c) | (d) |
+ | +------+
| | | (e) |
+----------+------+------+
To get the x coord of cell (e), we need to include cells (a) and (c), but they're not in the same row as us. We also can't just use the first row, as it may have horizontally-spanned elements included.
Thus this rather complex looking bit of code. Basically, we build a map of the table in memory, so that we can then "read off" the location of the cell. We short-circuit when we process "this", though.
See also comments on http://bytes.com/topic/javascript/answers/519470-misleading-cellindex-values-rowspan-colspan and source of http://www.javascripttoolbox.com/temp/table_cellindex.html .
*/
var rows = this.getParents('tr !> thead > tr'),
matrix = [],
row = null,
cells = null,
cell = null,
colspan = null,
rowspan = null,
rowIndex = null,
colIndex = null;
result.x = null;
for (var i = 0; i < rows.length && result.x === null; i++) {
matrix[i] = matrix[i] || [];
row = rows[i];
cells = row.getChildren('td, th');
for (var j = 0; j < cells.length && result.x === null; j++) {
cell = cells[j];
colspan = cell.get('colspan') || 1;
rowspan = cell.get('rowspan') || 1;
rowIndex = row.rowIndex;
matrix[rowIndex] = matrix[rowIndex] || [];
colIndex = null;
for (var l = 0; l <= matrix[rowIndex].length && colIndex === null; l++) {
if (!matrix[rowIndex][l]) colIndex = l;
}
if (cell === this) { // Short circuit if possible.
result.x = colIndex;
break;
}
for (var k = rowIndex; k < rowIndex + rowspan; k++) {
for (var l = colIndex; l < colIndex + colspan; l++) {
matrix[k] = matrix[k] || [];
matrix[k][l] = 1;
}
}
}
}
return result;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment