user244394
user244394

Reputation: 13448

How to make fixed table header scroll horizontally in sync with tbody data?

I have the following table with a fixed header. I want the header to be scrollable horizontally insync with the data? so that the header also scrolls horizontally when the user scrolls the tbody data horizontally. Is it possible to do that?

Note: I will be creating the table columns and header dynamically.. so sometime i can only have 2 columns sometimes 10 columns with 10 headers

Fiddle code

<table border="1">
    <thead>
        <tr>
            <th>head1</th>
            <th>head2</th>
            <th>head3</th>
            <th>head4</th>
              <th>head4</th>
        </tr>
    </thead>
    <tbody>
        <tr>

            <td>row 1, cell 1</td>
            <td>row 1, cell 2</td>
            <td>row 1, cell 2</td>
            <td>row 1, cell 2</td>
             <td>row 1, cell 2</td>
        </tr>
        <tr>
            <td>row 2, cell 1</td>
            <td>row 2, cell 2</td>
            <td>row 1, cell 2</td>
            <td>row 1, cell 2</td>
             <td>row 1, cell 2</td>
        </tr>
         <tr>
            <td>row 2, cell 1</td>
            <td>row 2, cell 2</td>
            <td>row 1, cell 2</td>
            <td>row 1, cell 2</td>
              <td>row 1, cell 2</td>
        </tr>
         <tr>
            <td>row 2, cell 1</td>
            <td>row 2, cell 2</td>
            <td>row 1, cell 2</td>
            <td>row 1, cell 2</td>
             <td>row 1, cell 2</td>
        </tr>
    </tbody>
</table>

table tbody
{
    display: block;
}
table thead
{
    display: block;
    overflow:auto;
}

table tbody 
{
   overflow: auto;
   height: 100px;
   position:absolute;
}

th
{
    width: 72px;
}

Upvotes: 0

Views: 1260

Answers (1)

Eric
Eric

Reputation: 18922

The only way to sync them is to listen to the scroll event, and update the header position accordingly. Something like this (assuming window is the container):

var headerEl = document.getElementById('yourHeadElement'); // or w/e
window.addEventListener('scroll', function(e){
    var offset = window.pageXOffset;
    headerEl.style.marginLeft = (-offset) + 'px';
    // alternatively:
    // headerEl.style.transform = 'translate3d('+ (-offset) +'px,0,0);';
}, false);

Note: You can even update the position by the transform property with translate/translate3d if you'd like to as well (instead of marginLeft).

If your container is not window, you will have to rely on the DOMElement.scrollLeft property. Happy coding!

Upvotes: 1

Related Questions