Toggle visibility of columns according to screen width

Toggle visibility of columns according to screen width

emanuelhmemanuelhm Posts: 1Questions: 1Answers: 0

Hello.

I've come up to a problem very similar to this one: https://datatables.net/forums/discussion/41818/hidden-columns-on-desktop-visible-only-on-tablet-mobile

I need a column to be visible on desktop and invisible (even on child row) under other displays.

In order to do this, I created a script, that obviously could be improved, but it might help others in the same situation.

var config = {
    columnDefs: [],
};

const breakPointConfiguration = {
    'dt-hide-desktop': (w) => w > 1024,
    'dt-hide-tablet-l': (w) => 768 < w && w <= 1024,
    'dt-hide-tablet-p': (w) => 480 < w && w <= 768,
    'dt-hide-mobile-l': (w) => 320 < w && w <= 768,
    'dt-hide-mobile-p': (w) => w <= 320,
};

var columns = table.querySelectorAll('thead tr:first-child th');

    for (var i = 0; i < columns.length; i++) {
        var screenWidth = window.screen.width;
        var classes = [...table.querySelectorAll('thead tr:first-child th')[i].classList];

        var hasVisibilityConfiguration = classes.some(function (value) {
            return value.includes('dt-')
        });

        if (!hasVisibilityConfiguration) {
            continue;
        }

        var isVisible = true;

        for (var j = 0; j < classes.length; j++) {
            if (breakPointConfiguration[classes[j]] == undefined) {
                continue;
            }

            if (breakPointConfiguration[classes[j]](screenWidth)) {
                isVisible = false;
            }
        }

        config.columnDefs.push({
            targets: [i],
            visible: isVisible,
        });
    }

$('#example-table').DataTable(config);

Basically, it looks for some classes in every table column and if it exists e check if the current screen width matches the criteria in order to hide it. Then it configures the datatable configuration object using 'columnDefs' option.

The classes could be used as follows:

<table id="example-table">
    <thead>
        <tr>
            <th class="dt-hide-desktop">Mobile</th>
            <th class="dt-hide-tablet-l dt-hide-tablet-p dt-hide-mobile-l dt-hide-mobile-p">Desktop</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Example 1</td>
            <td>Example 2</td>
        </tr>
    </tbody>
</table>

Best regards.

Answers

  • colincolin Posts: 15,177Questions: 1Answers: 2,590

    Nice, thanks for posting,

    Colin

Sign In or Register to comment.