Clickable Table Rows In HTML 2016-09-04

To make an entire row of a table clickable in HTML, as though you clicked a link in one of the columns, is pretty easy. I'll be using jQuery to demonstrate but the general concepts don't require it.

The first thing to do is to delegate a specific link as the action, in case there's more than one link in the given row. The other links will still work as normal, but if you click elsewhere in the table row, it'll use the delegated link. Just add a data attribute to specify this:

  <td><a href="example.html" data-row-link>Click Me</a></td>

And then a little JavaScript to tie up the action and change the cursor. Find all the links with our chosen attribute, walk up the DOM to find the containing table row, and then apply the style and click event to them.

$('a[data-row-link]').closest('tr').css('cursor', 'pointer').click(function(e) {

And that's it! Now if someone clicks anywhere on that table row, it'll execute the delegated link. If there's more than one link marked with data-row-link, it'll use the first one found. If no link is found with the attribute, the row behaves as a normal table row. An alternative way would be to find all the links in the current table row, and if there's just a single link, use that as the row link, but that's an exercise left for the reader.