Wednesday, April 6, 2011

HTML table row link

What is the best way to make a tables row a link? I currently am using jquery to zebra stripe the rows and also to highlight the onmouseover/off selected row so if js is the answer please use jquery.

From stackoverflow
  • Register a onclick event handler for the tr element. Something like this using jQuery:

    $("tr").bind("click", function(){ 
      window.location = 'http://www.example.com/'; 
    });
    
    Zaagmans : Doesn't this link you to the same location on every row click?
    Adones Cunha : You may use a hidden input in each tr to store the url.
    Ronny Vindenes : This will indeed bind the same link to each row, modify according to your needs..
  • $(document).ready(function(){
       $("tr").click(function(){
          /* personally I would throw a url attribute (<tr url="http://www.hunterconcepts.com">) on the tr and pull it off on click */
          window.location = $(this).attr("url");
    
       });
    });
    
  • I just use css:

    <style>
    table.collection {width:500px;border-collapse:collapse;}
    table.collection tr {background-color:#fff; border-bottom: 1px #99b solid;}
    table.collection tr:hover {background-color:#ffe;}
    table.collection td {display:table-cell;border-bottom: 1px #99b solid; padding:0px;}
    table.collection td a {text-decoration:none; display:block; padding:0px; height:100%;}
    </style>
    <table class="collection">
    <tr>
        <td><a href="#">Linky1</a></td>
        <td><a href="#">Data1</a></td>
    </tr>
    <tr>
        <td><a href="#">Linky2</a></td>
        <td><a href="#">Data2</a></td>
    </tr>
    </table>
    
    andybak : Best solution by far. Browser still see's this as a link so 'open in tab' or 'copy link' will work. The other solutions break my browser! There is scope for a JQuery solution that automates the above by DOM manipulation.
    troelskn : I'm having trouble with this solution. If one of the table cells contains enough content to wrap lines, the height of neighbouring cells won't stretch to the full height. Have you found a workaround for this case?
    Nick : This sounds like an IE quirks mode issue. I don't see this in firefox or IE 7-8 with "-//W3C//DTD XHTML 1.0 Strict//EN". It also may not work in IE 6 (but what does?)
    Nick : on second thought - adding height:100%; to the a style would most likely fix it (see the last edit).
    Simon D : height:100% doesn't fix it for me in FF 3.6, HTML5 doctype.

0 comments:

Post a Comment