October 25, 2024
Chicago 12, Melborne City, USA
javascript

DataTables Pagination Issue: Header hides with scrollX Option


I’m using DataTables, and everything works well, but I’ve encountered an issue when clicking on pagination: the table header hides, leaving only the table body visible. After some debugging, I discovered that the scrollX: true option is causing this problem. I attempted to remove the scrollX: true option and instead wrapped the parent element in a div with overflow enabled. However, this change resulted in scrollbar appearing below the pagination numbers, separate from the table itself.

<script>
$(document).ready(function() {
    // Initialize DataTables for all elements with the class 'example-table'
    var table = $('.example-table').DataTable({
         paging: true,
        
          fixedHeader: true,
          "scrollX": true, 
        searching: true,
        info: true,
        ordering: true,
        order: [],
        "scrollCollapse": true,
        dom: 'ifrtBp', // Add the buttons control element
        buttons: [
            {
                extend: 'excelHtml5',
                text: 'Export to Excel',
                titleAttr: 'Export as Excel'
             }
        ]
    });



    // Add event listener for print
    window.onbeforeprint = function() {
        // Disable horizontal scrolling and paging temporarily before printing
        table
            .columns.adjust()
            .draw(false); // Redraw table without changing page
        table.page.len(-1).draw(); // Show all entries

        // Disable overflow and scrolling for both header and body
        $('.dataTables_scrollBody').css('overflow', 'visible'); 
        $('.dataTables_scrollHead').css('overflow', 'visible');
    };

    window.onafterprint = function() {
        // Re-enable horizontal scrolling and restore paging after printing
        table.page.len(10).draw();

        // Restore overflow and scrolling for both header and body
        $('.dataTables_scrollBody').css('overflow', 'auto'); 
        $('.dataTables_scrollHead').css('overflow', 'auto');
    };
});
</script>



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video