Search code examples
jquerycss-positionhtml-tablefixed

Fixed First 3 rows in a table


Im having some problems with this.

I'm trying to set up the first 3 columns (letters) in the table to be fixed position when the rest scroll down (numbers).

/*---

JSFiddle with this table: http://jsfiddle.net/japeljoff/mVVN8/1/

<table>
<tr>
    <td>A</td>
    <td>B</td>
    <td>C</td>
    <td>D</td>
    <td>E</td>
</tr>
<tr>
    <td colspan="3">F</td>
    <td colspan="2">G</td>
</tr>
<tr>
    <td colspan="1">H</td>
    <td colspan="4">I</td>
</tr>
<tr>
    <td>0</td>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
</tr>
</table>

*/---

any ideas how to solve this problem?


Solution

  • It takes a bit of work and some jQuery, but you can do it by attaching to the scroll event of the window object. You have to mark those header rows as header rows (to make it easier for coding). Make sure to wrap your header rows in <thead></thead> and give the <table> itself an ID, in this example, "mytable".

    You have to add some CSS:

    .fixedTop {
      position: fixed;
      top: 0;
    }
    

    And JavaScript:

    var $rt = $("#mytable thead");
    
    var TableTop = $rt.offset().top;
    
    $(window).scroll(function () {
        if ($(window).scrollTop() > TableTop) {
            $rt.addClass("fixedTop");
        } else {
            $rt.removeClass("fixedTop");
        }
    });
    
    //Set widths of the header columns
    $("#mytable thead td, #mytable tbody td").width(function (i, width) {
        return $(this).width();
    });
    

    jsFiddle: http://jsfiddle.net/mVVN8/2/