Javascript – Making a Table Row clickable

htmljavascript

I wonder what the best way to make an entire tr clickable would be?

The most common (and only?) solution seems to be using JavaScript, by using onclick="javascript:document.location.href('bla.htm');" (not to forget: Setting a proper cursor with onmouseover/onmouseout).

While that works, it is a pity that the target URL is not visible in the status bar of a browser, unlike normal links.

So I just wonder if there is any room for optimization? Is it possible to display the URL that will be navigated to in the status bar of the browser? Or is there even a non-JavaScript way to make a tr clickable?

Best Solution

If you don't want to use javascript, you can do what Chris Porter suggested by wrapping each td element's content in matching anchor tags. Then set the anchor tags to display: block and set the height and line-height to be the same as the td's height. You should then find that the td's touch seamlessly and the effect is that the whole row is clickable. Watch out for padding on the td, which will cause gaps in the clickable area. Instead, apply padding to the anchor tags as it will form part of the clickable area if you do that.

I also like to set the row up to have a highlight effect by applying a different background color on tr:hover.

Example

For the latest Bootstrap (version 3.0.2), here's some quick CSS to show how this can be done:

table.row-clickable tbody tr td {
    padding: 0;
}

table.row-clickable tbody tr td a {
    display: block;
    padding: 8px;
}

Here's a sample table to work with:

<table class="table table-hover row-clickable">
    <tbody>
        <tr>
            <td><a href="#">Column 1</a></td>
            <td><a href="#">Column 2</a></td>
            <td><a href="#">Column 3</a></td>
        </tr>
    </tbody>
</table>

Here's an example showing this in action.