0

I was thinking if there's a better solution for adding onclick handler to each cell in a table than this approach: Adding an onclick event to a table row

Better in the way that I wouldn't need to set "cell.onclick = function" for each cell.

I just need to get the coordinations of a cell where user clicked.

Thanks!

EDIT: The "coordinations" mean 0x0 for top-left cell, 0x1 for second cell in the first row etc.

Community
  • 1
  • 1
Martin Vseticka
  • 25,160
  • 25
  • 118
  • 187
  • 2
    use JQuery and bind a function to the click event for all the ``'s at once: `$("td").live('click', function(){});` – dnagirl Apr 21 '10 at 17:52

2 Answers2

7

Are you looking for this?

$(function(){
    $("#tableId tr td").click(function(event) {
       alert(event.pageX);
       alert(event.pageY);
    });
});

In case your table cells are generated dynamically:

$(function(){
    $("#tableId tr td").live('click', function(event) {
       alert(event.pageX);
       alert(event.pageY);
    });
});

.

Update Based On OP Comment:

To get top and left values you could try this:

$(function(){
    $("#tableId tr td").click(function(event) {
       alert($(this).offset().top);
       alert($(this).offset().left);
    });
});

As your other comment shows, you are probably looking to get the IDs of the clicked cell, you may try this:

$(function(){
    $("#tableId tr td").click(function(event) {
       alert($(this).attr('id'));
    });
});

But for the above to work, it is assumed that all cells already have an id attribute.

Sarfraz
  • 355,543
  • 70
  • 511
  • 562
0

You're looking for event delegation.

http://icant.co.uk/sandbox/eventdelegation/

among other examples. Basically observe some higher container such as the table for click events and then determine if you care to handle it by inspecting the event passed to the event handler.

So if the click happens inside the table, you can determine the target of the event and assuming there's a valid td present handle the event.

This has the benefit of allowing you to dynamically add more table cells without needing to add handlers to all of them.

jQuery in particular as an excellent delegate method for using this approach. http://api.jquery.com/delegate/

mczepiel
  • 686
  • 3
  • 12