Changing datatable scrollY to fill parent's space

Changing datatable scrollY to fill parent's space

dennywdennyw Posts: 3Questions: 1Answers: 0

I am trying to get a datatable to dynamically adjust it's scroll height to fill its parent's space. I found this article:
https://datatables.net/forums/discussion/30255/automatically-resize-table-if-parent-container-size-was-changed
Which is similar in that it changes the pagination to try to make the table fit its parent's space, but I don't want pagination, I just want to update scrollY. Does anyone have the un-obfuscated code that I could modify? Or has someone already done this?

Answers

  • colincolin Posts: 15,142Questions: 1Answers: 2,586

    Hi @dennyw ,

    It sounds like this here is closer to what you want. It resizes the vertical as the parent container changes shape,

    Cheers,

    Colin

  • dennywdennyw Posts: 3Questions: 1Answers: 0

    Using vh helps a little,but it's still not very good. What I really need is an event to recalculate the vertical space and set scrollY to the correct number of pixels.

  • colincolin Posts: 15,142Questions: 1Answers: 2,586

    Hi again,

    Have a look at this blog post here - https://datatables.net/blog/2017-12-31 . The plugin used there should do the trick! Sorry for not picking that up before,

    Cheers,

    Colin

  • dennywdennyw Posts: 3Questions: 1Answers: 0
    edited March 2019

    I found a solution. Assuming your DataTable is in a div with an id of TableContainer and your table has an id of example. This works:

    <script>
        function resizePage() {
            const container = $("#TableContainer");
            const height = container.height() - container.find(".dataTables_scrollHead").height();
            updateDataTable(height + "px");
        };
    
        var resizeTimer;
    
        $(window).resize(function() {
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(resizePage, 100);
        });
    
        function updateDataTable(scrollHeight) {
            $('#example').DataTable(
                {
                    destroy: true,
                    paging: false,
                    "bFilter": false,
                    "bInfo": false,
                    scrollY: scrollHeight,
                    columnDefs: [{ width: "16%", targets: 0 }]
                }
            );
        }
    
        $(document).ready(function() {
            updateDataTable('1px'); // give it any height, it will be changed by the timer event, but it needs some size for the page to work
            resizeTimer = setTimeout(resizePage, 100);
        });
    </script>
    
This discussion has been closed.