0

I'm using jquery.panzoom to contain a table.

Each table cell is in this form:

<td><div class="cell" id="cell-24-14"></div></td>  

The table is created dynamically, so I use this to try and catch an event:

$('.cell').on('click', function (e) {        
        alert($(this).attr('id'));
});

I've tried removing the divs, and catching the clicks on the td's directly, but this didn't work as well.
When I'm catching clicks on any div, I see that the containers of the table are catching the clicks, but the clicks never get to the table itself (and not to its cells).

How do I catch click events on an individual div inside a td (or even a td)?

Oren A
  • 5,870
  • 6
  • 43
  • 64
  • what exactly are you trying to do? – Chanckjh Jan 25 '15 at 05:44
  • bind click to a div which is in a td. it's a game and the grid is a table.. not sure I'm answering your question, what do you mean specifically? – Oren A Jan 25 '15 at 09:16
  • 1
    you're not able to register an event handler on `div` element in a dynamically created table is it so ? if yes, try registering your click handler, the one you posted in the question, in the same function where you're appending your dynamic table to the DOM i.e just move to your code to that appendToDOM function – Arkantos Jan 25 '15 at 09:54
  • @Arkantos - can you make that an answer so that I can mark it? Thanks. – Oren A Feb 05 '15 at 09:20

1 Answers1

2

You can actually move your event binding to the function where these elements are added to DOM like this

function appendToDOM(){
   // creating a td element and appending to DOM
    var td = $('<td><div class="cell" id="cell-24-14"></div></td>');
    td.appendTo($table);

   /* now that the element is available in DOM, you can define you event handler here*/

    $('.cell').on('click', function (e) {        
       alert($(this).attr('id'));
    });
}

The problem with this approach is you're defining an event handler for every .cell element in your table, you can do better by using delegation.

$('urClosestStaticParent').on('click','.cell',function(e){
    alert($(this).attr('id'));
});

You can call this code just before you're displaying the table, like a finishing touch :)

When I say closest static parent, i'm talking about the parent of the dynamic table that you're creating, probably a div container which is there from the document load. If you don't have any such element, you can try adding some empty div in your html, append your table to that and use that, if not use document instead.

Arkantos
  • 6,530
  • 2
  • 16
  • 36