Search code examples
javascripthtmlcsshtml-tablescrollable

Scrollable table ideas (tricky)


I've been wrestling with this for some time now. Say that I have a table that has many rows and many columns (overflows the page vertically and horizontally). I want to fix the first row (thead) in place.

The catch: I want the vertical and horizontal scrollbars to ALWAYS be visible. i.e., I don't want the user to have to scroll horizontally to find the vertical scroll bar, and vice versa.

The best I could come up with is to split the thead and tbody into two separate tables with synchronized scrolling, but this creates problems with alignment and matching cell widths, so I'd rather not.

How would you go about solving this?


Solution

  • To anyone who wants to achieve a similar effect:

    Wrap your table in a div with width:100%; and overflow:auto;.

    Copy the header portion of your table and create a new table with just that in it. POSITION THIS TABLE AS ABSOLUTE! (position:absolute;)

    Place your header table in the same div as the real table. (It should fit perfectly over the original header portion).

    Use jQuery to manage the scrolling of the div and stick the header in place...

    jQuery(document).ready(function() {
        jQuery('#tableDiv').scroll(function() {
            jQuery('#copiedHeaderTable').css('top', jQuery(this).scrollTop());
        });
    })
    

    This solution of course makes a few assumptions about your requirements, but has a few advantages (simplicity being the main).

    Edit To ensure matching cell widths, wrap all th contents in a div and set the width of each div manually before the cloning:

    jQuery('#headerRow th div').each(function() {
        jQuery(this).css('width', jQuery(this).parent()[0].offsetWidth+'px');
    });