Sticky Table Header using jQuery

Last Updated: October 21, 2019

Complete Tutorial – Coming Soon

<style>
    td{
        vertical-align: middle!important;
    }
    .table-fixed-header.fixed-header thead {
        position: fixed;
        top: 0px;
        background: white;
        z-index: 9999;
    }
    </style>
<script>
    jQuery(document).ready(function(){
        
        var tableFixedHeader = $('.table-fixed-header');
        
        var tableFixedHeaderHead = tableFixedHeader.find('thead');
        var tableFixedHeaderBody = tableFixedHeader.find('tbody');
        
        tableFixedHeaderHead.css('width', tableFixedHeaderHead.outerWidth());
        tableFixedHeaderBody.css('width', tableFixedHeaderBody.outerWidth());
        
        tableFixedHeaderHead.find('th').each(function(){
            $(this).css('width', $(this).outerWidth() );
        });
        
        tableFixedHeaderBody.find('td').each(function(){
            $(this).css('width', $(this).outerWidth() );
        });
        
        $(window).scroll(function(){
            checkTableHeader();
        });
        
        $(window).load(function(){
            checkTableHeader();
        });
        
        function checkTableHeader(){
            if ($(window).scrollTop() >= tableFixedHeader.position().top - 30) {
               tableFixedHeader.addClass('fixed-header');
            }
            else {
               tableFixedHeader.removeClass('fixed-header');
            }
        }  
    });  
    
    </script>