views:

213

answers:

2

I was thinking if there's a better solution for adding onclick handler to each cell in a table than this approach: http://stackoverflow.com/questions/1207939/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.

+2  A: 

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
The first example works but rather than position in pixels I need positions in the table (like 0x0 for top-left cell).
MartyIX
I can add as IDs of cells the coordinations - it would work nice if I can get from "event" the ID of clicked cell.
MartyIX
@MartyIX: It is not possible to get ids from the event object.
Sarfraz
$("#" + this.ed + " tr td").click(function(event) { $.dump(this.id); }); This works for me well and yes, it's not from event object.
MartyIX
@MartyIX: I have updated my answer as far as i could understand your question and your comments. Thanks
Sarfraz
Offset is pixel-based. I need logical offset and from IDs it can be separated.
MartyIX
Thank you, it's what I was looking for!
MartyIX
@MartyIX: Thank God and you are welcome :)
Sarfraz
A: 

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