JSFiddle - React, Tailwind, and code Playground

by Ilmv

HTML

<table id="datagrid">
    <thead>
        <tr>
            <th>A</th>
            <th>B</th>
            <th>C</th>
            <th>D</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>This is a really, really, really, really long column</td>
            <td>Foo</td>
            <td>Bar</td>
            <td>Boo</td>
        </tr>
    </tbody>
</table>

<br />

CSS

table {
    width: 100%; 
    border-collapse: collapse;
    margin-top: 10px;
}

th, td {
    border: 1px solid black;   
}

td {
    height: 0;   
}
.cloned tbody {
    visibility: hidden;  
    display: none;
}

JavaScript

// I need to completely hide tbody whilst maintaining the column widths
// in thead.
// display: none; will NOT maintain the column widths
// visibility: hidden; does, but the table height remains even though
//    tbody isn't visible. I cannot set height: 0;
$(document).ready(function() {

    fix_table_header();
    header_resize();

    $(window).resize(function() {

        header_resize();


    });

});

function fix_table_header() {


    $('table').each(function() {

        var $self = $(this),
            random_number = randomFromTo(1, 9999999999);

        if ($self.hasClass('parent') || $self.hasClass('cloned')) {
            return false;
        }

        var $cloned = $self.clone();

        $cloned.find('tbody, tfoot').remove();
        $cloned.addClass('cloned');
        $cloned.data('parent', 'parent-' + random_number);

        $self.after($cloned);

        $self.addClass('parent parent-' + random_number);





    });

}

function header_resize() {

    $('.cloned thead th').each(function() {

        var $self = $(this),
            col_index = $self.index(),
            $cloned = $('.' + $self.parents('table').data('parent')),
            th = $cloned.find('thead th').eq(col_index),
            width = th.width();

        var borders = parseInt(th.css('border-left-width'), 10) + parseInt(th.css('border-right-width'), 10);
        
        // honestly no idea why I have to hald borders to maintain proper
        // width, must investigate
      
        $(this).css('width', width + borders / 2);

    });


}

function randomFromTo(from, to) {
    return Math.floor(Math.random() * (to - from + 1) + from);
}