HTML table row click-able with link

You can not make a table row click-able using HTML alone. By click-able, I mean nesting an entire row inside an anchor tag, as follows:

HTML

 <a href="example.html"><tr><td>example table data</td></tr></a>

This is not valid mark-up as an anchor tag is an in-line element and therefore you should not nest a table row inside it.

Javascript to the rescue

You can how ever write a simple piece of Javascript to achieve the same end. jQuery makes this even simpler. The following snippet will link any table row to example.html.

jQuery

 $("tr").click(function(){
   window.location = "example.html";
 });

If you want to specify a specific table or table row, then you need to adjust the selectors accordingly. For example, if I have a table that has a class of "myclass", then I would use the following jQuery:

jQuery

 $(".myclass tr").click(function(){
   window.location = "example.html";
 });

Add a bit of style

The Javascript above achieves the desired functionality, but as it stands a user will not know that a row is clickable because it will look like any other table row. An easy way to make users aware that they can click on the row to change the cursor to a pointer and change the background colour of the row if the user hovers on the row. The snippet below will achieve this:

CSS

 tr:hover{
  cursor: pointer;
  background-color: #ccc;
}

Of course, this will work on any table row. But if you want to specify a particular table, like we did in the jQuery example above, then simply make the CSS more specific, as follows:

CSS

 .myclass tr:hover{
  cursor: pointer;
  background-color: #ccc;
}

Comments

wow, looks like wadmans nailed it again.

sry doesnt work

I think you have shared some of the very great information and i really appreciate your work.

Post new comment

The content of this field is kept private and will not be shown publicly.

Learn how to become a Drupal developer

Does Drupal development make your head explode and drive you crazy?

Why not learn from someone who has paved the way instead?

Sign up to my upcoming learning series.

Syndicate

Syndicate content

Hello!!

I am Blair Wadman and this is where I write about Drupal, PHP, CSS etc

Stuff

© Blair Wadman
2005 - 2011