Why do headers become misaligned when using ColVis and ScrollX

Why do headers become misaligned when using ColVis and ScrollX

matthttammatthttam Posts: 40Questions: 2Answers: 0

I am using datatables in a new project and I have been adding features I want in the tables including serverSide processing, tableTools, and colVis. I am using Bootstrap 3 and everything is working pretty well. I was having issues with the table overflowing to the right of my container when the data was too wide and since my background is a dark grey and my table container is white the table was unreadable when hanging off the white.

To fix this I enabled scrollX and said to hide overflow. This works great and is more user friendly for mobile devices. But... if I remove columns and add them back using colVis, the header widths no longer match the data below them. Sorting or searching the table fixes the header widths instantly.

I'm guessing I should call draw() after a column add but I wanted to see if there was a better solution.

I am using Chrome.

There is a similar issue in http://www.datatables.net/release-datatables/extensions/FixedColumns/examples/colvis.html
Where removing and re-adding columns and scrolling right causes the data to scroll but the headers to remain stationary.

For some reason I can't get colvis to work at all using live.datatables.net otherwise I would recreate the issue for you. Enabled the library for ColVis 1.1.1 just returns "Script error. (line 0)"

Here is my datatable initilization partial:

<script type="text/javascript" charset="utf-8">
    $(document).ready(function() {
        var html_table = $('<%= '#'+table_id.to_s %>')
        // Initialize Table
        var datatable_table = html_table.DataTable(
                {
                    //dom: 'T<"clear">lfrtip',
                    dom: '<"col-md-4" l><"col-md-4" T><"col-md-4"f><"col-md-12"C>rtip',

                    scrollX: true,
                    //scrollCollapse: true,
                    // Include export buttons
                    tableTools: {
                        sSwfPath: "<%= asset_path('copy_csv_xls_pdf.swf') %>"
                    },
                    // Include Restore, Show all, and Show none options in column visibility plugin for datatables
                    colVis: {
                        restore: "Restore",
                        showAll: "Show all",
                        showNone: "Show none"
                    },
                    processing: true,
                    serverSide: true,
                    ajax: '<%= server_side_path %>',
                    columns: <%=raw column_options.to_json() %>
                }
        );
        /*var tt = new $.fn.dataTable.TableTools( datatable_table, {
            sRowSelect: 'single'
        } );*/
        //$( tt.fnContainer() ).insertAfter('div.info');

        // Create Column Searches
        html_table.find('tfoot th').each( function() {
            var title = html_table.find('thead th').eq( $(this).index()).text();
            $(this).html( '<input type="text" placeholder="Search '+title+'" />');
        });

        datatable_table.columns().every( function () {
            var that = this;
            console.log(this)
            $( 'input', this.footer()).on( 'keyup change', function () {
                console.log(this)
                that
                        .search( this.value)
                        .draw();
            })
        })


    } );
</script>

I am using the bootstrap gem, font-awsome, a custom theme called sb-admin found here http://startbootstrap.com/template-overviews/sb-admin/ and the tools i've added.
aplication.css.sass - (At symbol excluded due to profile linking)

import "bootstrap-sprockets"
import "bootstrap"
import "dataTables.bootstrap.css"
import "font-awesome-sprockets"
import "font-awesome"
import "plugins/morris"
import "sb-admin"

import "dataTables.tableTools.css"
import "dataTables.colVis.css"

Here is the datatable html.erb partial. I use server side so tbody is empty. But I did get that working after several hours of learning ruby :-P

<!--<div class="container-fluid">-->
<!--<div class="panel panel-default">
  <div class="panel-heading">Panel heading
  <div class="panel-body">-->
<div class="row">
    <div class="col-md-12">
        <div class="panel-body">
          <table id="<%= table_id %>" class="display table table-striped table-bordered" cellspacing="0" width="100%">
            <thead>
            <tr>
              <% column_names.each do |column| %>
                  <%= content_tag('th',column) %>
              <% end %>
              <!--<th>Actions</th>-->
            </tr>
            </thead>
            <tbody>

            </tbody>

            <tfoot>
            <tr>
              <% column_names.each do |column| %>
                  <%= content_tag('th','') %>
              <% end %>
            </tr>
            </tfoot>
          </table>
        </div>
    </div>
</div>
  <!--</div>
</div>
</div>-->

This question has an accepted answers - jump to answer

Answers

  • matthttammatthttam Posts: 40Questions: 2Answers: 0

    I just noticed that when adding any column using ColVis I am getting an error in console:
    "Uncaught TypeError: Cannot read property 'style' of undefined" - From jquery.datatable.min

    Also, here is the code once rendered... just realized that things are obscured with variables.

    $(document).ready(function() {
            var html_table = $('#students')
            // Initialize Table
            var datatable_table = html_table.DataTable(
                    {
                        //dom: 'T<"clear">lfrtip',
                        dom: '<"col-md-4" l><"col-md-4" T><"col-md-4"f><"col-md-12"C>rtip',
    
                        scrollX: true,
                        scrollCollapse: true,
                        // Include export buttons
                        tableTools: {
                            sSwfPath: "/assets/copy_csv_xls_pdf-51b135065fad2997492266c3d4735ccc8589d2d91472f274624667e8a9af82dd.swf"
                        },
                        // Include Restore, Show all, and Show none options in column visibility plugin for datatables
                        colVis: {
                            restore: "Restore",
                            showAll: "Show all",
                            showNone: "Show none"
                        },
                        processing: true,
                        serverSide: true,
                        ajax: '/datatable/students_server_side',
                        columns: [{"data":"student_number","name":"student_number","visible":true,"title":"Student ID"},{"data":"first_name","name":"first_name","visible":true,"title":"First Name"},{"data":"last_name","name":"last_name","visible":true,"title":"Last Name"},{"data":"id","name":"id","visible":true,"title":"ID","searchable":false},{"data":"created_at","name":"created_at","visible":true,"title":"Created At","searchable":false},{"data":"updated_at","name":"updated_at","visible":true,"title":"Updated At","searchable":false}]
                    }
            );
            /*var tt = new $.fn.dataTable.TableTools( datatable_table, {
                sRowSelect: 'single'
            } );*/
            //$( tt.fnContainer() ).insertAfter('div.info');
    
            // Create Column Searches
            html_table.find('tfoot th').each( function() {
                var title = html_table.find('thead th').eq( $(this).index()).text();
                $(this).html( '<input type="text" placeholder="Search '+title+'" />');
            });
    
            datatable_table.columns().every( function () {
                var that = this;
                console.log(this)
                $( 'input', this.footer()).on( 'keyup change', function () {
                    console.log(this)
                    that
                            .search( this.value)
                            .draw();
                })
            })
    
    
        } );
    
  • matthttammatthttam Posts: 40Questions: 2Answers: 0

    OK, I tried creating an event on column visibility to mybe find out out what is going on.

    html_table.on( 'column-visibility.dt', function ( e, settings, column, state ) {
                console.log(
                        'Column '+ column +' has changed to '+ (state ? 'visible' : 'hidden')
                );
            } );
    

    When hiding the columns I get console entries. When showing them, that error stops whetever is happening in its tracks. I tried clicking Show All and only 1 column appears, mis-alligned, and the error apperas.

    "Uncaught TypeError: Cannot read property 'style' of undefined"

    If I comment "scrollX: true" everything works perfectly. scrollX seems really buggy. Does anyone know what to try? I just want the table to not flow off page at all and turn into a horizontal scroll if it is larger than the width provided.

    Thanks!

  • matthttammatthttam Posts: 40Questions: 2Answers: 0

    Well after explaining it that way it hit me to use style="overflow-x: scroll" on my page wrapper div. This did what I wanted. But, I must say scrollX and colVis do not get along.

  • kynisakynisa Posts: 1Questions: 0Answers: 0

    Hi.
    I faced the same issue, thanks for explanation here.
    I also commented "scrollX: true" and added style="overflow-x: scroll" to the wrapper.

  • alawson107alawson107 Posts: 3Questions: 1Answers: 1
    Answer ✓

    I was getting the same error message and I switched to the development version (Build: 24th Jul 2015, 15:39) and it seems to work fine.

This discussion has been closed.