Fix a column while scrolling horizontally in jQuery DataTable
— jQuery, DataTable, Quick Tip — 1 min read
This tutorial will teach you how to implement a fixed or sticky column in a jQuery DataTable while scrolling horizontally.
Initial Setup
First we'll setup a basic DataTable in jsFiddle with some dummy data sourced from the official DataTable website.
Check out the code in jsFiddleIn the DataTable configuration options, we have specified that we want to scroll both ways, horizontally as well as vertically and that the vertical height should be 500px
with the help of scrollX
and scrollY
properties.
$(document).ready(function() { $("table.my-table").DataTable({ pageLength: 100, scrollX: true, scrollY: 500 });});
Solution for fixing the first column while scrolling
There are three things you must do in order to achieve this.
Step 1: Include the FixedColumns Extension's CSS and JS.
<link href="https://cdn.datatables.net/fixedcolumns/4.3.0/css/fixedColumns.dataTables.min.css" rel="stylesheet"><script src="https://cdn.datatables.net/fixedcolumns/4.3.0/js/dataTables.fixedColumns.min.js"></script>
The CSS and JS versions of the FixedColumns extension used above are the latest ones available at the time of writing this tutorial. You should use the version that is compatible with the version of the core DataTable plugins that you are using in your project.
Step 2: Refactor the <td>
tags of the column you want to fix as table headers i.e <th>
tags.
Step 3: Add the fixedColumns
property to the DataTable options during initialization and set it to true
.
$(document).ready(function() { $("table.my-table").DataTable({ pageLength: 100, scrollX: true, scrollY: 500, fixedColumns: true });});
This will enable the first column to be fixed while scrolling horizontally.
Check out the code in jsFiddleHope this helps!🙏