Search code examples
csscolorscss-tables

CSS: set color for selected row in a table


I need to add the following feature to my table:

When the user clicks on a row (selects it), the row is marked with the color #FFCF8B (the same as hover). I tried #newspaper-b tbody tr.selected td, but it does not work.

   #newspaper-b {
        border-collapse: collapse;
        border-color: #B7DDF2;
        border-style: solid;
        border-width: 1px;
        font-family: Arial,Helvetica,sans-serif;
        font-size: 11px;
        margin: 0;
        text-align: left;
        width: 480px;
    }
    #newspaper-b th {
        background: none repeat scroll 0 0 #EBF4FB;
        border-color: lightgray;
        font-size: 11px;
        font-weight: bold;
        padding: 15px 10px 10px;
    }
    #newspaper-b tbody tr td {
        background: none repeat scroll 0 0 #FFFFFF;
    }
    #newspaper-b td {
        border-top: 1px dashed #FFFFFF;
        color: #000000;
        padding: 10px;
    }
    #newspaper-b tbody tr:hover td {
        background: none repeat scroll 0 0 #FFCF8B;
        color: #000000;
    }
    #newspaper-b tbody tr.selected td {
        background: none repeat scroll 0 0 #FFCF8B;
        color: #000000;
    }

Solution

  • In order to add a .selected class to your clicked row you need a bit of JavaScript.

    Example http://jsfiddle.net/thebabydino/KzVfy/

    I used jQuery for the example, so there is very little code:

    $("tr").click(function(){
        $(this).addClass("selected").siblings().removeClass("selected");
    });​
    

    Of course, it can be done without using any library if you don't wish to include jQuery.


    Just for variation, I did another version. This one uses no library (no jQuery, no Mootools, no YUI, no Dojo, and so on...) and selects multiple rows. Can be seen at http://jsfiddle.net/thebabydino/nY5jj/ with a variation that unselelects a selected row when clicking on it again http://jsfiddle.net/thebabydino/nY5jj/1/

    The JavaScript is:

    var trs = document.querySelectorAll("tr");
    for(var i = 0; i < trs.length; i++){
        trs[i].addEventListener("click", function(){this.className += " selected";});
    }​
    

    To unselect a selected row when clicking on it a second time :

    var trs = document.querySelectorAll("tr");
    for(var i = 0; i < trs.length; i++){
        trs[i].addEventListener("click", function(){
            var cn = this.className, thc = " selected", start_idx = cn.indexOf(thc);
            if(start_idx == -1) cn += thc;
            else cn = cn.replace(thc,"");
            this.className = cn;
        });
    }​