How Do I Make a Full Table Row Clickable?

It's a common scenario to display an HTML table with items, like products, employees and so on, and then link each item to a detail page where you can display the full details of this item.

The link is often represented by a button or text link in one of the columns. But to make it easier for your users to select a specific item, you could make the full row clickable. With a bit of JavaScript, this is pretty easy to do.

Often when people try to implement this behavior, they try to add an HTML link to each table cell, like this:

<table>
<tr> <td><a href="Details.asp">John</a></td> <td><a href="Details.asp">Doe</a></td> </tr>
</table>

The disadvantage of this method is that not the entire table cell is linked, but just the text in that cell. You also need to add a lot of extra code to make each cell clickable.

To make the full row selectable, you should add the link to the <tr> instead of to individual table cells. Since you're not allowed to place an <a> tag around a table row, you'll have to think a little bit outside the box to solve this puzzle. Instead of using the <a> tag, you can implement a click handler with a JavaScript method attached to it for the table row as in the example below. To clearly communicate to the user that the entire table is clickable, I also added some code that changes the background color of the table row when the mouse hovers over it. This makes it easier to see which row is selected.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" 
             content="text/html; charset=iso-8859-1" />
    <title>Full Row Select</title>
    <script type="text/javascript">
    function ChangeColor(tableRow, highLight)
    {
    if (highLight)
    {
      tableRow.style.backgroundColor = '#dcfac9';
    }
    else
    {
      tableRow.style.backgroundColor = 'white';
    }
  }

  function DoNav(theUrl)
  {
  document.location.href = theUrl;
  }
  </script>
</head>
<body>
  <table width="100%" border="1" cellpadding="0" cellspacing="0">
  <tr onmouseover="ChangeColor(this, true);" 
              onmouseout="ChangeColor(this, false);" 
              onclick="DoNav('http://www.yahoo.com/');">
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>
  <tr onmouseover="ChangeColor(this, true);" 
              onmouseout="ChangeColor(this, false);" 
              onclick="DoNav('http://www.microsoft.com/');">
    <td>4</td>
    <td>5</td>
    <td>6</td>
  </tr>
  <tr onmouseover="ChangeColor(this, true);" 
              onmouseout="ChangeColor(this, false);" 
              onclick="DoNav('http://Imar.Spaanjaars.Com/');">
    <td>7</td>
    <td>8</td>
    <td>9</td>
  </tr>
  </table>
</body>
</html>

On each <tr> element I have added the onclick attribute that calls the DoNav method. This will take the user to a new page whenever the user has clicked somewhere in the table row. To change the color of the rows when the mouse hovers over the table, I have also added the onmouseover and onmouseout attributes that call the ChangeColor method to change the background color of the table row.

You can check out a working example of this code. In the example I also added a bit of CSS to influence the borders of the table, so each row has a nice thin black border at the top and bottom side, but not between the columns on the left and right side. Look at the source of the page in the browser to see how it is done.





Where to Next?

Wonder where to go next? You can read existing comments below or you can post a comment yourself on this article.



Feedback by Other Visitors of Imar.Spaanjaars.Com

On Monday 5/9/2005 9:54:18 PM Luis said:
if you use firefox or an equivalent browser you can replace the onmouseover and onmouseout by a css style: tr:hover {background-color: Yellow; cursor: pointer;}.

On Wednesday 4/19/2006 7:55:09 PM Ronne said:
Very helpful, thanks a lot!

On Wednesday 4/26/2006 11:46:33 AM wayne said:
nice script.. does anyone know how to impliment the cursor: pointer command over the cell??? it doesnt seem to be working...

Also, i when the page loads the cell has no border by default... so when mouseover over the cell occurs the page moves when border is added.. which is not a good thing.. any ideas to correct this bug??

thx ;)

On Wednesday 4/26/2006 8:54:53 PM Imar Spaanjaars said:
Hi Wayne,

Are you saying you have no border initially, but want to add one when you hover? In that case, the easiest thing to do is to *add* a border when the page initially loads, but you should give it the same color as the background. That way, the border is already there, taking up its space, and it only changes its color when you hover.

To change the cursor, you should be able to do something like this:

tableRow.style.cursor="hand";

tableRow.style.cursor="pointer";

Hope this helps,

Imar

On Thursday 4/27/2006 9:49:05 AM Giorgio said:
Thx, great solution. Very simple!!!

On Monday 7/24/2006 5:59:15 PM Kevin Field said:
There's only one drawback to this solution (which I was using already)--the UI of the web browser becomes broken in that the user no longer has the option of "open in a new tab/window" in the context menu...and emulating this is painful and sketchy.  Is there any way to have the functionality of surrounding a TR with an A without breaking W3C specs?

Kev

On Tuesday 7/25/2006 10:49:20 PM Imar Spaanjaars said:
Hi Kevin,

Yeah, good point.

I see at least two fixes (work arounds, actually).

One is to use the old method, where each td contains an a tag that spans the entire cell (using display:block and an explicit width).

Alternatively, you could use JavaScript to detect whether the shift key was pressed and then open a new window instead of opening a new page in the same window....

Cheers,

Imar

On Monday 7/31/2006 2:58:35 PM Kevin Field said:
Thanks Imar...I'll have to think about it.  I found out most of my users don't ever use tabs or new windows, so I guess it'd just be for me.  ;)  Anyway, I might end up just sending row data from the server using JSON and building the page from the data using JavaScript, so if I'm doing that anyway, I think I might end up using the 'old method' you cited.

Thanks again,
Kev

On Monday 7/31/2006 8:43:04 PM Imar Spaanjaars said:
Hi Kevin,

You're welcome....

Imar

On Tuesday 2/27/2007 6:29:38 AM Art said:
Your script saved the day!  Thanks to all your inputs.

On Wednesday 3/21/2007 9:30:06 PM Doug said:
In the DoNav part of the code, is it possible to assign a target in the url?  I can't seem to make a target work.

Any help would be appreciated.

Thanks,

Doug

On Wednesday 3/21/2007 10:58:32 PM Imar Spaanjaars said:
Hi Doug,

You'd use window.open instead. Do a Google search for it combined with the word JavaScript and you'll find many examples, including an explanation of all the options for the open function.

Cheers,

Imar

On Monday 8/27/2007 6:53:23 PM Paul said:
Hi, thanks for your script, it is helping me a lot : ) I am trying to customize a thing. For example, my link is:

[a href="img/port/001.jpg" rel="lightbox[test]"][img border="0" src="img/port/001.jpg" width="109" height="80"][/a]

So in the onclick I use:

[onclick="DoNav('img/port/001.jpg);"]

and it is working ok. But I really need to use the rel="lightbox[test]" with the onclick event. Do you think it is possible to do it using this script?

Thanks for a great, simple and efficient script.

On Monday 8/27/2007 8:58:45 PM Imar Spaanjaars said:
Hi Paul,

Sorry, I don't understand what you mean. Can you elaborate?

Imar

On Monday 8/27/2007 9:24:27 PM Paul said:
Hi Imar,

Thanks for the reply ^^

Well, actually I am trying to use this: http://www.huddletogether.com/projects/lightbox2/

So, to use this i need to put rel="lightbox" in the link line (note the PART 2 from the LightBox webpage).

So, there is a way to write a text in a cell and use your script to click in the cell and load the LightBox? I think there is a possibility to the DoNav function handle this, but I dunno why.

Thanks again for the reply. ^^

On Monday 8/27/2007 9:35:56 PM Imar Spaanjaars said:
Hi Paul,

Right, I see. I don't think so, or you may need to change the lightbox scripts.

As far as I know, lightbox intercepts the click on the link, finds the rel attribute and acts accordingly. I don't think (or at least I don't know how to do it) it will work with JavaScript generated clicks.

Sorry,

Imar

On Friday 11/2/2007 7:31:51 AM robin said:
I have the following code which i like it to open in a new window and have the script pass a varialble to then next script. neither is working and could use some help with it.

[snip].....

this is emp_details.php
?php
echo "[br]Test ==:";
$testing = $_POST['test'];
echo  $testing;

it prints test==: but it doesn't echo the variable passed through the url
http://localhost/testing/emp_details.php?test=2

On Friday 11/2/2007 7:34:23 AM Imar Spaanjaars said:
Hi robin,

Isn't that because of this:

$testing = $_POST['test'];

You pass values through the query string, yet you try to get the value from the post variables collection.

Hope this helps,

Imar

On Thursday 12/20/2007 10:37:48 AM ken said:
How would I target an iframe window with this code?

document.location.href=myLink

my iframe name is myscreen

On Thursday 12/20/2007 8:18:53 PM Imar Spaanjaars said:
Hi ken,

You can access the frames collection:

document.frames['iframename'].src = .....

HtH,

Imar

On Friday 12/21/2007 7:27:23 AM Ken said:
Thanks alot!  It works great!  

http://www.medievalstudios.com

I'm working on the new site now.

On Friday 4/11/2008 2:09:56 AM Steven said:
Great script. Thanks a bunch.

I am working on a PHP application which requires one to login. Once logged in, and one visits the current.php page for the first time, which lists a bunch of TR's in which I am using your DoNav function to link to another php page it logs the user out of the system. When the user logs back in and repeats the process it works just fine.

This only occurs the first time. Any future attempts to perform the same action allows for the link to work and open the php page I am linking to.

Do you think this is a problem with the JavaScript or PHP? Do you have any suggestions?

Thanks

On Friday 4/11/2008 7:47:32 AM Imar Spaanjaars said:
Hi Steve,

That sounds like a PHP coding logic error. Try posting this (with code) on one of the numerous PHP forms. I think the Wrox forum (p2p.wrox.com) has PHP categories as well.

Cheers,

Imar

On Monday 6/9/2008 5:02:12 PM Brendan said:
I am using your code in a table that pulls info from a database and is created with PHP.  Since I put your code within the PHP code I had to change your double quotes to single quotes, otherwise its the same.  the ColorChange function works but I cannot get the onclick function to work.  Any suggestions?  Thanks.

On Monday 6/9/2008 7:36:40 PM Imar Spaanjaars said:
Hi Brendan,

Try posting this, with source code, on a forum like http://p2p.wrox.com You'll get much better PHP support.

Cheers.

Imar

On Tuesday 9/30/2008 11:12:48 PM Martin said:
Thankyou very much, very useful

On Thursday 1/29/2009 8:43:50 AM Rei said:
Thanks!

On Monday 2/2/2009 6:52:49 AM Andrea said:
To implement hand pointer cursor change:

onmouseover="ChangeColor(this, true);"

to

onmouseover="ChangeColor(this, true), style.cursor='pointer';"

Thank you Imar for sharing a very useful script!

On Saturday 3/28/2009 4:04:58 PM Rambabu said:
Thanks for providing such good and easily understandable example.

On Wednesday 4/29/2009 2:22:05 PM YM said:
Great script. Is there anyway to display tooltip when mouse over? thanks,

On Wednesday 4/29/2009 9:03:26 PM Imar Spaanjaars said:
Hi YM,

You can apply a title attribute to the table row or to the individual table cells.

Alternatively, you may want to look into jQuery or other client side JavaScript frameworks.

Cheerd,

Imar

On Wednesday 5/6/2009 9:32:46 PM shanti said:
Hi ,

  Onclick i am trying to submit the form and unable to do so.Please help

On Wednesday 5/6/2009 11:12:28 PM Imar Spaanjaars said:
Hi shanti,

I guess that all depends on the code you are using to submit. Can you post this on the Wrox forum (http://p2p.wrox.com/index.php?referrerid=385) as it's not so easy to post code here. If you send me the link I'll take a look. If it's related to this post, I'll try to come up with a reply.

Cheers,

Imar

On Thursday 5/7/2009 1:54:40 PM YM said:
Appling a title attribute to the table row shows as tooltip. Thank you Imar!

On Thursday 6/4/2009 8:26:49 AM Thomas Bill said:
This may be of use...

To have the link open in a new window simply change to the java script from document.location.href = theUrl;  to   window.open(theUrl);

e.g:

  function DoNav(theUrl)
  {
window.open(theUrl);
}

On Wednesday 6/24/2009 6:56:54 PM king said:
Is there a way to exclude one section of the row from being clickable? I have a text field I also use to enter on the row that I would like a user to be able to click and select to enter text, but not automatically follow the link.

On Wednesday 6/24/2009 7:21:17 PM Imar Spaanjaars said:
Hi king,

Haven't tried it but you could try handling onclick on the textbox and return false; it seems that event is bubbling up....


Imar

On Thursday 8/6/2009 1:49:57 PM Lea said:
Hello could somebody help me
How i change this function :
function DoNav(theUrl)
  {
window.open(theUrl);
}
into this one. :
function nad()
{ if (DOGODEK_LINK_ID != '')
{
self.location.href  = 'crm_dogodek.php?DOGODEK_ID=' + DOGODEK_ID
+'&POD_ID='  + DOGODEK_ID;
}
else {
self.location.href  = 'crm_dogodek.php?DOGODEK_ID=' + ''
+'&POD_ID='  + DOGODEK_ID;
}
    
     }
Iwont that when I click on row I call a function witch gives an ID into other table on the same side.
P.S sorry about a language I'm a slovenian girl

On Thursday 8/6/2009 3:08:19 PM Imar Spaanjaars said:
Hi Lea,

I am not sure I understand what you want. What are you trying to accomplish?

Imar

On Friday 8/7/2009 2:38:30 AM david said:
Nice !

How would you modify your code so that when a row was clicked only the data on that row would be sent to a form submit?

thanks

On Friday 8/7/2009 8:01:18 AM lea said:
Hello Imar
I wont that when I click on a table row send ID from one table to another but in the same page not url. just a function..
My code is:

function clickOnTableRow()
{
var tableObj = this.parentNode;
if(tableObj.tagName!='TABLE')tableObj = tableObj.parentNode;
if(activeRowClickArray[tableObj.id] && this!=activeRowClickArray[tableObj.id]){
activeRowClickArray[tableObj.id].className='DOGODEK_ID';
}
this.className = arrayOfClickClasses[tableObj.id];
activeRowClickArray[tableObj.id] = this;
}

now this just do that when I click th row become red now I wont that when I click goes ID from Up table into down table.
A code for send ID is:

function nad(ID, LINK_ID)
{

if (LINK_ID != '')
{
self.location.href  = 'crm_dogodek.php?ID=' + ID
+'&POD_ID='  + ID;
}
else {
self.location.href  = 'crm_dogodek.php?ID=' + ''
+'&POD_ID='  + ID;
}     
        }
This code I heva to give into code onclick.
If You won't I can send you all my code but not here in a form.
Please help me I'm triing this two days and nothing.

Lea

On Friday 8/7/2009 8:13:47 AM Imar Spaanjaars said:
Hi lea,

Rather than sending me the code, can you post it in one of the JavaScript categories of the Wrox forums located here: http://p2p.wrox.com/index.php?referrerid=385 and then send me the link?

Makes it easier to share code and for others to join - and learn from - the discussion. If you post there, please be sure to provide more information as I still don't understand exactly what you want.

Cheers,

Imar

On Friday 8/7/2009 8:15:01 AM Imar Spaanjaars said:
Hi david,

You can store the ID (or another value) of the row in a hidden form field and then call document.forms[0].submit() to programmatically submit the form.

Hope this helps,

Imar

On Friday 8/7/2009 8:47:17 AM lea said:
Hi i send it on http://p2p.wrox.com/java-basics-199/ , but i don't see my post anywhere. Maybe its not in yet.

On Friday 8/7/2009 8:50:11 AM lea said:
Whats this where should I send my comment?

Hello lejka, our records indicate that you have never posted to p2p.wrox.com Forums before! If you have a programming question, please make your first post by asking your question in the right forum for the question. Or become part of the community by providing a useful answer to someone else's question. Be sure to only post your question to the right forum and respect other members. Thanks! Post to win prizes! Post more to increase your chances of being Wrox’s top poster of the month.
Lea

On Friday 8/7/2009 9:22:28 AM Imar Spaanjaars said:
Hi lea,

I don't know. Did you sign up for an account at Wrox? Did you have to confirm it somehow?

Imar

On Friday 8/7/2009 9:44:17 AM lea said:
this function is for click on row

// snip, code cut by imar //

I don't wont to have a picture in a table but just a row on click wich send ID in a teble in the same said. I think I just have to give this to code together but i don't know how.

LEA

On Friday 8/7/2009 7:04:37 PM Imar Spaanjaars said:
Hi lea,

Please try the wrox forum again. It's a much better place to share code. I'll be more than happy to help you with this (once I figure out what it is that you want) but we need a better place to post code. The Wrox forum is a good place for this. Please spend some time on the site to find out how it works, sign up for an account and then post a message with *clear details* about what it is you're after. After three posts, I still don't understand you.
Please note: the Wrox forum is not my forum, so I cannot answer questions as to how it works.

Cheers,

Imar

On Saturday 8/29/2009 9:33:58 AM Vikram said:
I had a different problem. I wanted to make an entire row clickable except for one cell because it had a checkbox.

[tr onclick="fn2()"]
    [td]some element[/td]
    [td]some element[/td]
    .....
    [td onclick="fn1()"]a checkbox is here[/td]
[/tr]

what I did was:
1. created an onclick event for that cell and set a variable to true when the onclick event  for that cell was called.
2. Then the row already had the onclick event written (which i didnt want to execute). so I checked the variable at the begining of the fn.
if(checkboxWasClicked) {checkWasClicked = false; return;}
The false is given to reset the flag.

Here is the pseudo code:

var checkboxWasClicked = false;
fn1()
{
    checkboxWasClicked = true;
}
fn2()
{
    if (checkboxWasClicked) {
        checkboxWasClicked = false;
        return;
        }
    //some other code that should execute if clicked on row except for that cell.
}

I got this idea from the above examples.
So Thanks a lot.

On Friday 1/15/2010 4:51:00 PM Hugh Abbott said:
loved this !

Talk Back! Comment on Imar.Spaanjaars.Com

I am interested in what you have to say about this article. Feel free to post any comments, remarks or questions you may have about this article. The Talk Back feature is not meant for technical questions that are not directly related to this article. So, a post like "Hey, can you tell me how I can upload files to a MySQL database in PHP?" is likely to be removed. Also spam and unrealistic job offers will be deleted immediately.

When you post a comment, you have to provide your name and the comment. Your e-mail address is optional and you only need to provide it if you want me to contact you. It will not be displayed along with your comment. I got sick and tired of the comment spam I was receiving, so I have protected this page with a CAPTCHA image now. This means that if you want to leave a comment, you'll need to type in the text you see on the image. If you can't see the text clearly, click the New Image button to get an image with a new text. For more details, see this news item.

If you want to object to a comment made by another visitor, be sure to contact me and I'll look into it ASAP. Don't forget to mention the page link, or the QuickDocId of the document.
For more information about the Talk Back feature, check out this news item


Captcha Image - Please type the text from the image in the text box
Can't see the text on the image? Click the New Image button to display a new image with different text.