Making a table row (tr) clickable with jQuery (with an a href link, and hover!?)

26,239

Solution 1

Assuming it's a "normal" link (not a Javascript trigger) this will be sufficient:

$("tr").click(function() {
  window.location.href = $(this).find("a").attr("href");
});

You will probably want to communicate this behaviour to the user in some way. The minimal approach would be changing the cursor while hovering over the row.

Solution 2

I found this solution to work well for me.

$('table tr').live("click",function(e){ 
    if (e.target instanceof HTMLInputElement || e.target instanceof HTMLAnchorElement){
        return;
        }
        alert('works');
});

Solution 3

If you have another link inside the table, like a delete link, you may want to use the event object to check if the user clicked over that particular link and avoid the redirection.

Example HTML:

<tr title="http://path/to/download">
  <td><img src="img/icons/file_pdf.png"></td>
  <td><a href="/path/to/delete">Delete</a></td>
  <td>(01/03/10)</td>
</tr>

Example JavaScript:

$("tr").click(function(event) {
  if(event.target.nodeName != "A"){
    window.location.href = $(this).attr("title");
  }
});

Usually my tables have an action cell with edit and delete, so I use the row click event to redirect to the show action.

Share:
26,239
Nick
Author by

Nick

Updated on July 05, 2022

Comments

  • Nick
    Nick almost 2 years

    Just a (hopefully) quick question, I have the following HTML code:

    <tr>
     <td><img src="img/icons/file_pdf.png"></td>
     <td><a href="../upload/1267473577.pdf">Bulletin 1st March 2010</a></td>
     <td>(01/03/10)</td>
    </tr>
    

    Ideally I'd like a way to grab the a href link using jQuery and make it so that no matter where you click on that particular table row, it will take you to that link.

    Is there any way to do this? I can do it via icky inline JavaScript as an absolute last resort, but since finding out about jQuery I quite like the idea of being able to do this cleanly and unobtrusively :-)

  • Nick
    Nick about 14 years
    This is great, thanks cletus! I'll use this, but also add a couple of different classes for different states and switch between them on hover - change the background colour, and also the cursor as you suggested.
  • Ben Hull
    Ben Hull about 12 years
    The problem with this solution (and all the others I've found), is that you're assuming all clicks on the row should load the links location in the browser. What about right-clicks? or cmd/ctrl+clicks? These wouldn't natively cause this behaviour...