Macha Macha - 1 year ago 62
Javascript Question

How to get a cell's location

I'm writing a script which manages a very large table. When a user clicks a table cell, I would like to know which cell they clicked.

| | |
| | Click|

should give me a cell reference of (1, 1).

Any way I could do this with javascript. The page it's running on uses jquery for other purposes, so any jquery based solutions are good aswell.

EDIT: To clarify, the top left cell is (0, 0). For performance reasons, the event needs to bound to the table, not the tds.

Answer Source

This is done very easily using the target property of the event object:

$('#mytable').click(function(e) {
    var tr = $('tr');
    var x = $('tr', this).index(tr);
    var y = tr.children('td').index($(;
    alert(x + ',' + y);

This approach allows you to only bind 1 event handler to the entire table and then figure out which table cell was clicked. This is known as event delegation and can be much more efficient in the right situation, and this one fits the bill. Using this you avoid binding an event to each <td>, and it does not require hard-coding coordinates. So, if your table looks like this:

<table id='mytable'>

It will alert the coordinates on click. You can do whatever with that. :)

If you find performance to be too slow (depending on just how large your table is) you would then have to resort to hardcoding or a combination of the two, maybe only hard coding the <tr> index, as that would be the slowest to get, and then getting the <td> index dynamically. Finally, if all this coordinate business is completely unnecessary and what you really just wanted was a reference to the clicked <td>, you would just do this:

$('#mytable').click(function(e) {
    var td = $(;
    // go crazy
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download