'jQuery Datatable Show / hide columns dynamically

I am trying to show/hide datatable columns dynamically. For this, here I am going with the example which is given by the official datatable website.

This is the code for my datatable:

HTML:

<table id="itemEdit" class="table collapsed">
    <thead>
      <tr>
        <th>ID</th>
        <th>SKU</th>
        <th>Barcode</th>
        <th>Item Name</th>
        <th>Price</th>
      </tr>
    </thead>

    <tbody></tbody>
</table>

JS:

var tableId = "#itemEdit";
var $_table = $(tableId).DataTable({ 
    //dom:            "Bfrtip",
    scrollY:        "300px",
    scrollX:        true,
    scrollCollapse: true,

    "ajax": './view_items.php',
    "columns": [            
      {"data": "id", "class": "align-middle"},
      {"data": "sku","class": "align-middle"},            
      {"data": "barcode","class": "align-middle"},            
      {"data": "itemname","class": "align-middle"},            
      {"data": "price","class": "align-middle"},            
    ]
})

HTML for <a>:

<div class="btn-group dropright dd-backdrop">
    <button type="button" class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
      <span class="sr-only">Columns</span>
    </button>
    <div class="dropdown-menu p-0 ">
      <a href="#" class="dropdown-item toggle-vis" data-column="4">
        Item Name
      </a>
    </div>
</div> 

My question is, just I want to add CSS class for the a.toggle-vis base on its visibility.

I tried it something like this. But its not working for me.

$('a.toggle-vis').on('click', function (e) {
    e.preventDefault();

    // Get the column API object
    var column = $_table.column($(this).attr('data-column'));

    //console.log(column)

    if (column.visible() === true) {
      $(this).addClass('showing').removeClass('not-showing');
      column.visible(!column.visible());
    } else {
      $(this).removeClass('showing').addClass('not-showing');
      $(this).removeClass('active');
    }
       
    $_table.columns.adjust().draw( false ); // adjust column sizing and redraw
});

Hope somebody may help me out.



Solution 1:[1]

In the end, your approach is correct - with one small change: Move the following line (which toggles the column's visibility)...

column.visible(!column.visible());

...from inside the if statement to before the if statement.

That will ensure the toggle always happens for the selected column.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 andrewJames