wyatt wyatt -4 years ago 62
CSS Question

A static row in an HTML table

I'm trying to create a file listing a la windows explorer in HTML/Javascript. As such, I'd like the first row of the table, which contains the headings for all the columns, to be visible even when the columns are scrolled.

I've tried a few options involving placing the headings in a separate table, but all have failed for primarily one reason - when the file list is scrolled horizontally, the headings table does not scroll with it.

Hence, I'm essentially looking for an element linked to another in such a way that it scrolls with the other horizontally, but not vertically.

I realize many will think I should be using css and not tables, but this is moot as even using css I can't solve the problem of wanting the header bar to scroll with the files horizontally, but not vertically.

Any help you can offer would be greatly appreciated.

Answer Source

My suggestion is to use Javascript. Hook to the onScroll event of both scrollable elements, and on the event update the scrollLeft property of both elements.

    var tableHeader = document.getElementById('tableHeader');
    var tableBody = document.getElementById('tableBody');

    function updateTableBody(e){
        tableBody = tableHeader.scrollLeft;
    }

    function updateTableHeader(e){
        tableHeader = tableBody.scrollLeft;
    }    

    tableHeader.addEventListener('scroll', updateTableBody, false);
    tableBody.addEventListener('scroll', updateTableHeader, false);

Of course, this is not bulletproof and could be optimized, but it will give you and idea and hopefully a good start.

NOTE: Make sure both element have the same dimensions, otherwise, the scroll will have a weird offset.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download