Bootstrap 5 - Dynamic Table Stripes


Posted by Blake on 11/28/2021

In looking for a lighter weight alternative to the capable DataTables (you know the one) I stumbled across Simple-DataTables which is a no depdendency ES2018 code base with minimal bulk. It appears to provide many of the features I need so I had began work on implementing ASP.NET Core HTML helper extensions to make re-implementing a breeze.

I'm currently using Bootstrap 5 (although this should work with any table tag implementation). I noticed that although I was able to apply some classes to the dynamically created table some did not work, notably table-striped. In order to get that working I used jQuery to dynamically set the alternating color on each row (setting a CSS class would also work). Here is both the jQuery example and the Simple DataTables snippet as well (which shows how to ajax in a JSON dataset). Note that here I'm looking at all visible tr elements on the page, if you wish to laser focus your implementation you can change the selector to be whatever you need.

jQuery Only

$("tr:visible").each(function (index) {
    $(this).css("background-color", !!(index & 1) ? "rgba(0,0,0,.05)" : "rgba(0,0,0,0)");
});

Simple-DataTables Implementation

HTML

<!-- Blank table placed where we would like it with an ID we will reference in the JavaScript -->
<table id="dt">
</table>

JavaScript

// The route to your JSON api or static JSON file.
fetch(`/api/data.json`)
    .then(response => response.json())
    .then(data => {
        let table = new simpleDatatables.DataTable("#dt", {
            perPage: 10,
            searchable: true,
            fixedHeight: false,
            data: {
                headings: Object.keys(data[0]),
                data: data.map(item => Object.values(item))
            },
        });

        // Init code that should run on the table, this is where we'll set our
        // custom striping.
        table.on('datatable.init', function() {
            $("tr:visible").each(function (index) {
                $(this).css("background-color", !!(index & 1) ? "rgba(0,0,0,.05)" : "rgba(0,0,0,0)");
            });
        });
    });