Linking entire table rows
There is no easy way to link up a whole table row since you cannot wrap an <a>
tag around a <tr>
tag.
There are two approaches to solve this
- use javascript to bind to the onclick event of the table row
- put an anchor tag inside every table cell of the row
Both of these approaches have issues:
- Using the first method will result in people who have javascript disabled not being able to follow that link. Moreover, If you link up a file, users will not be able to do things like right-click -> save as
- Using the second method will result in a smaller click target since it is hard to make the anchor tags always expand to the full width and height of the table cells
That's why it makes sense to combine those two approaches.
Advantages
- The entire row will always be clickable (and trigger a hover effect)
- Users can use right-click -> save on almost the entire surface of the row
- Users without javascript can still follow the link
HTML
<tr data-href="linkToFile.pdf">
<td>
<a href="linkToFile.pdf">Column one</a>
</td>
<td>
<a href="linkToFile.pdf">Column two</a>
</td>
<tr>
CSS
*[data-href] {
cursor: pointer;
}
td a {
display:inline-block;
min-height:100%;
width:100%;
padding: 10px; /* add your padding here */
}
td {
padding:0;
}
We try to make the anchor tag use all available space. This does not work well for empty cells (a
can help a little) as well as in cases where some table cells have multiple lines. Hence the following javascript.
Javascript (using jquery)
$('*[data-href]').on("click",function(){
window.location = $(this).data('href');
return false;
});
$("td > a").on("click",function(e){
e.stopPropagation();
});
The key here is to use stopPropagation
to prevent the click event from bubbling up to the row
Written by dommmel
Related protips
2 Responses
More specific selectors are better for performance on jQuery. So, use $('tr[data-href]')
, instead.
I've had luck with <td><a href="x"><div>[text]</div></a></td>
Then I just repeat for every cell in the row. It's html heavy, but I generate tables with php so it's not a lot of coding work.
Javascript and I don't know each other very well yet :)