Search code examples
datatablesdatatables-1.10

Datatables direct insertion of colvis button


I'm using Datatables and have the colvis button working:

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs/jszip-2.5.0/dt-1.10.22/b-1.6.5/b-colvis-1.6.5/b-html5-1.6.5/datatables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/v/bs/jszip-2.5.0/dt-1.10.22/b-1.6.5/b-colvis-1.6.5/b-html5-1.6.5/datatables.min.js"></script>

datatable = $('.datatableclass').DataTable( {
  dom: 'Bfrtip',
  buttons: ['excelHtml5','colvis']
});

But I'm trying to place the colvis button somewhere else - alongside the rest of my buttons rather than using the default datatables buttons group.

This is what I have tried:

<script>
datatable = $('.datatableclass').DataTable( {
  buttons: ['excelHtml5','colvis']
});

datatable.buttons('.buttons-colvis').container().appendTo( $('#colvis-div') );
</script>
...
<div id="colvis-div"></div>

This works, but includes the entire button group (export + colvis buttons). I only want to show the colvis button.


Solution

  • You can use the Buttons API to handle this. Here is one way:

    First create your Excel button in the usual way, but do not create the colvis button:

    table = $('#example').DataTable( {
      dom: 'Bfrtip',
      buttons: ['excelHtml5']
    } );
    

    Then use the API to create the colvis button:

    new $.fn.dataTable.Buttons( table, {
      name: 'colvis-button',
      buttons: ['colvis']
    } );
    
    table.buttons(1, null).container().appendTo( $('#colvis-div') );
    

    In the above snippet, the buttons(1, null) selector is documented here. The 1 refers to the second (zero-indexed) button group that was created.

    There are additional ways to select the required group, if you don't want to use its index. So, for example, using the name will also work:

    table.buttons('colvis-button', null).container().appendTo( $('#colvis-div') );
    

    In my case, the end result is this, with the colvis div added below the table:

    enter image description here