Make an entire table row clickable with jQuery
Posted December 22nd, 2009 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> </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:
- Set multiple attributes at once with jQuery (Tuesday, December 15th 2009)
- Modify right-click menu behavior with jQuery (Friday, December 11th 2009)
- Assign and remove a click handler from an element with jQuery (Tuesday, December 1st 2009)
- CSS cursor property (Saturday, September 5th 2009)
- Add an offsite link icon after external links with jQuery (Saturday, March 28th 2009)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.
