how can i add a listener to a table column?

In order to execute something when a column is clicked, you can add one event listener to the whole table and then check which column was clicked, then execute some code.

Using window.event.target.cellIndex you can access the cell index.

Using window.event.target.parentNode.rowIndex you can access the row index.

document.getElementById('myTbl').addEventListener('click', function(event) 

{
  var col = window.event.target.cellIndex;
  var row = window.event.target.parentNode.rowIndex;
  if (col==1){
        alert('Col index is: ' + col + '\nRow index is: ' + row);
  }
});
table, td {
    border: 1px solid black;
}
<table id="myTbl">
    <thead>
        <tr>
            <th>name</th>
            <th>lastname</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Guga</td>
            <td>Nemsitsveridze</td>
        </tr>
        <tr>
            <td>Giorgi</td>
            <td>Beshidze</td>
        </tr>
    </tbody>
</table>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top