Make an entire table row clickable with jQuery

Posted in HTML and CSS and Javascript -

If an HTML table row contains only one <a> link it can be useful to make the entire row clickable and make it activate that link. This post shows how to make the entire row clickable with jQuery so that clicking anywhere in the row is the same as clicking that link.

Working Example

This example shows what I'm referring to. If you are reading this post in a feed reader then click through to view this in a web browser otherwise it will not work. Clicking the links in this example will show the link in an alert dialog instead of following the link.

  Name Description Price
Edit Apples Blah blah blah blah 10.23
Edit Bananas Blah blah blah blah 11.45
Edit Oranges Blah blah blah blah 12.56

The HTML

Here's the HTML behind the above example:

<table id="example">
<tr>
    <th>&nbsp;</th>
    <th>Name</th>
    <th>Description</th>
    <th>Price</th>
</tr>
<tr>
    <td><a href="apples">Edit</a></td>
    <td>Apples</td>
    <td>Blah blah blah blah</td>
    <td>10.23</td>
</tr>
<tr>
    <td><a href="bananas">Edit</a></td>
    <td>Bananas</td>
    <td>Blah blah blah blah</td>
    <td>11.45</td>
</tr>
<tr>
    <td><a href="oranges">Edit</a></td>
    <td>Oranges</td>
    <td>Blah blah blah blah</td>
    <td>12.56</td>
</tr>
</table>

The CSS

And the CSS:

table#example {
    border-collapse: collapse;   
}
#example tr {
    background-color: #eee;
    border-top: 1px solid #fff;
}
#example tr:hover {
    background-color: #ccc;
}
#example th {
    background-color: #fff;
}
#example th, #example td {
    padding: 3px 5px;
}
#example td:hover {
    cursor: pointer;
}

The jQuery

And finally the jQuery which makes the magic happen:

$(document).ready(function() {

    $('#example tr').click(function() {
        var href = $(this).find("a").attr("href");
        if(href) {
            window.location = href;
        }
    });

});

What it does is when a row is clicked, a search is done for the href belonging to an anchor. If one is found, the window's location is set to that href.



Related posts:


Comments