Reputation: 2721
I want to create clickable rows in an html table. Each row should be a link leading to a different page. I can of course add onclick
handler, but that will create kind of a crappy UI - poor accessibility, no keyboard navigation, no right/middle click...
I found a better way to do it. Instead of using normal table
element, force div
s to act as different table tags through css display
rules. And for rows, use a
-s, with appropriate href attribute.
Here's what I mean:
.table {
display: table;
border-collapse: collapse;
font-family: sans-serif;
width: 100%;
}
.thead {
display: table-header-group;
}
.tbody {
display: table-row-group;
}
.td, .th {
display: table-cell;
padding: 5px 10px;
text-align: center;
}
.tr {
display: table-row;
}
.thead > .tr {
background: #ccc;
color: #555;
}
a.tr {
text-decoration: none;
color: black;
}
a.tr:hover {
background: #eee;
cursor: pointer;
}
<div class="table">
<div class="thead">
<div class="tr">
<div class="th">ID</div>
<div class="th">Name</div>
</div>
</div>
<div class="tbody">
<a class="tr" href="524.html">
<div class="td">524</div>
<div class="td">John Smith</div>
</a>
<a class="tr" href="331.html">
<div class="td">331</div>
<div class="td">Miles Corner</div>
</a>
</div>
</div>
Note how rows are clickable, you can tab through them and there is a nice tooltip showing link you will go to. Much better than onclick.
If I use a framework like React, I don't even have to replace all elements with div-s. I can just add <a>
tags instead of <tr>
s and it will work.
My question is, what's the catch? What am I missing? Is there some accessibility, browser compatibility, or other reason not to do this?
Upvotes: 1
Views: 775
Reputation: 6160
There are some catches, and I would suggest another UI pattern that is more accessible and more versatile:
Use the cells with the primary key (or the most important information for the user), to place an <a>
around it's text. In your case, this would probably be the Name-column.
<td><a href="…">John Simth</a></td>
This not only solves your issue with accessibility, but also with other design considerations that we typically have in tables.
aria-role
, but it's not recommended and support might vary. This structure is important to navigate inside the table, usually by means of arrow keys (grid navigation).tr:focus
class and style your row differently)Upvotes: 1