Explain Codes LogoExplain Codes Logo

Html - table row like a link

html
responsive-design
clickable-space
css-padding
Nikita BarsukovbyNikita Barsukov·Sep 7, 2024
TLDR

You can transform a table row into a fully clickable link using a combination of JavaScript event handlers and adequately styled anchor tags:

<style> .full-width-link { display: block; width: 100%; height: 100%; /* Like sardines in a can... */ } </style> <table> <tr onclick="window.location='https://www.example.com'; /*Freely teleporting to another dimension...*/"> <td><a href="https://www.example.com" class="full-width-link">Click me, c'mon, it will be fun!</a></td> <td>Stay here, I dare you to not click!</td> </tr> </table>

The class .full-width-link makes the anchor cover the entire cell space, reducing the dreadful dead space and boosting clickability.

Eliminating dead space

When it comes to web navigation, every pixel counts. Minimize non-clickable space by tweaking your CSS padding and maintaining the clickable area:

td, th { padding: 0; /* Sayonara, padding! */ } .full-width-link { display: block; width: 100%; height: 100%; padding: 10px; /* Here's some padding, but inside the anchor! */ }

Using modern Javascript

While jQuery is undoubtedly powerful, the built-in JavaScript querySelectorAll and addEventListener methods offer a slicker solution for adding clickablility:

document.querySelectorAll('tr[data-href]').forEach(row => { row.addEventListener('click', () => { window.location = row.dataset.href; // Fancy teleportation trick! }); });

Using data-href to store the URL not only makes your code readable but also easy to maintain.

To bypass the headache of dealing with block elements inside <a> tags, opt for the humble <span>:

<td> <a href="https://www.example.com" class="full-width-link"> <span class="link-content">I'm safe and clickable!</span> </a> </td>

Experimenting with Flexibility

Swapping out table elements for divs with CSS table properties opens up new avenues for flexibility. Coupled with JavaScript's powerful onClick event, your control over the functionalities widens.

Cross-Browser Compatibility Check

Styling anchors to mimic tables can sometimes lead to compatibility issues across different browsers and devices. Always remember to test on multiple platforms.