Scrolling Header of a Table

As we scroll the table stays at the top so that the user must not scroll up to view the table headings.

by Daniele Cedro

HTML

<p>this is a paragraph that i'm willing to test </p>
<table id="table-1">
    <thead>
        <tr>
            <th>Col1</th>
            <th>Col2</th>
            <th>Col3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>info</td>
            <td>info</td>
            <td>info</td>
        </tr>
        <tr>
            <td>info</td>
            <td>info</td>
            <td>info</td>
        </tr>
        <tr>
            <td>info</td>
            <td>info</td>
            <td>info</td>
        </tr>
    </tbody>
</table>
<table id="header-fixed"></table>
<p>this is a paragraph that i'm willing to test </p><p>this is a paragraph that i'm willing to test </p><p>this is a paragraph that i'm willing to test </p><p>this is a paragraph that i'm willing to test </p>

CSS

body { height: 100%; }
table  {border:1px solid red;}
#header-fixed { 
    position: fixed; 
    top: 0px; display:none;
    background-color:white;
}

JavaScript

var tableOffset = $("#table-1").offset().top;
var $header = $("#table-1 > thead").clone();
var $fixedHeader = $("#header-fixed").append($header);

$(window).bind("scroll", function() {
    var offset = $(this).scrollTop();
    
    if (offset >= tableOffset && $fixedHeader.is(":hidden")) {
        $fixedHeader.show();
    }
    else if (offset < tableOffset) {
        $fixedHeader.hide();
    }
});