Responsive Datatables with Automatic Column Hiding

Responsive Datatables allows automatic column hiding based on the size of the viewport. The responsiveness can be added by specifying class=’responsive’ in the HTML or by setting the responsive option as true while initializing Datatable. The automatic column hiding will happen from the right by default. That is, the rightmost columns will be hidden when the viewport width is getting smaller. We can also customize to hide particular columns by defining responsive priority while initializing Datatables. We can also use HTML5 data attributedata-priority to specify the custom priority to the columns.

In this tutorial, I have added examples for the responsive Datatables to customize column priority for the automatic column hiding. These examples are used to see how to define column priority by using columnDef option at the time of initialization and by using HTML5 data-priority attribute. In a previous tutorial, we have seen how to calculate the column-wise total using Datatables Footer callback.

Initializing Datatable with Responsive Column Priority

In this example, I used columnDef property to specify the responsive priority to the Datatable columns. While initializing the Datatables, I specified the priority and the target index of the columns. The following script shows how to initialize a Datatable with automatic column hiding by setting responsive as true and defining column priority. In this example, it has five columns First Name, Last Name, Address, Phone and DOB. I set priority 1 and 2 to the columns First Name and DOB respectively. So, when the viewport size is small then the columns will be hidden automatically based on the priority set to the columns.

Output

The following screenshot shows the output of this example.

Customizing Column Priority using HTML5 Data Attribute

In this example, I used the HTML5 data-priority to specify the column priority with the Datatable HTML. In this code, I have added the class=responsive to let the Datatable be responsive in the smaller viewport. I set last two columns Phone and DOB with the priority 1 and 2 respectively.