Concealing columns in DataTables based on designated screen sizes

Issue

I am facing a challenge with two DataTables — one with five columns and the other with four columns. My goal is to find a solution for hiding certain columns based on specific screen widths.

Approaches I've Tested

While resizing the browser, both tables automatically switch to a two-column layout when the width reaches 480 pixels. However, I require additional breakpoints in between to hide more columns that do not fit within the viewport.

  • Attempted adding a responsive class to the table similar to the example shown here
  • Experimented with using column control helper classes to eliminate columns at specific breakpoints, but even the none class did not hide a column
  • Assigned classes to the <th> elements in the thead section to leverage their responsive breakpoints
  • Included responsive: true in my DataTables configuration options

scripts.js

$('#test-scores').dataTable({
        initComplete: function () {
            this.api().columns([0,1,2]).every( function () {
                var column = this;
                var colIdx = column.index();
                // adjust label for dropdown according to index
                // TODO - colIdx is producing 0
                if (colIdx === 0) {
                    var label = 'districts';
                }
                else if (colIdx === 1) {
                    var label = 'schools';
                }
                else {
                    var label = 'subjects';
                }

                var select = $('.select--map-' + label)
                    .on( 'change', function () {
                        var val = $(this).val();
                        if ( val == '*' ) {
                            column
                                .search( '' )
                                .draw();
                        }
                        else {
                            val = $.fn.dataTable.util.escapeRegex( val );
                            column
                                .search( val ? '^'+val+'$' : '', true, false )
                                .draw();
                        }
                    });

                column.data().unique().sort().each( function ( d, j ) {
                    select.append( '<option value="'+d+'">'+d+'</option>' )
                });
            });
        },
        "pageLength": 25, // The number of entries per page
        "order": [0, 'asc'], // First column in ascending order, previous "3, desc"
        "responsive": true,
        "searching": true,
        "columns": [
        { "data": "district",
            "render": function (data, type, row, meta) {
                return '<a href="/schools/' + makeSlug(data) + '">' + data + '</a>';
            }
        },
        { "data": "school",
            "render": function (data, type, row, meta) {
                return '<a href="/schools/' + makeSlug(row['district']) + '/' + makeSlug(data) + '">' + data + '</a>';
            }
        },
        { "data": "subject" },
        { 
            "data": "rate",
            "render": $.fn.dataTable.render.number( ',', '.', 1, '', '%' ) 
        },
        { 
            "data": "test_takers", 
            "render": $.fn.dataTable.render.number( ',', '.', 0, '', '' ) 
        }
        ],
        "ajax": {
            "url": "{% static 'schools/json/school_map_scores.json' %}"
                }
    });

index.html

<table id="test-scores" class="table table-striped responsive" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th class="table-district none">District</th>
            <th class="table-school none">School</th>
            <th class="table-subject none">Subject</th>
            <th class="table-proficiency none">Pct. proficient</th>
            <th class="table-testtakers none">No. of test takers</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

Answer №1

The concept presented above is a bit confusing to me. Could it be possible that you are making the issue more complex than necessary? I suggest exploring the column.visible() method and handling the onresize event. Here is a straightforward example:

var table = $('#example').DataTable({
  autoWidth: false //keep this as false to maintain the intended design
}) 

Create an onresize handler to automatically hide columns on smaller screens:

window.onresize = function() {
  var screenWidth = this.innerWidth;
  table.column(5).visible(screenWidth > 700);
  table.column(4).visible(screenWidth > 600);
  table.column(3).visible(screenWidth > 500);
  table.column(2).visible(screenWidth > 400);
  table.column(1).visible(screenWidth > 300);  
}
//trigger the resize event upon page load
$(window).trigger('resize');

Check out the demo here -> http://jsfiddle.net/4xL6d5xa/

Feel free to adjust the size of the bottom right panel.


var table;
window.onresize = function() {
  if (!table) return;
  var w = this.innerWidth;
  table.api().column(5).visible(w > 700);
  ...
}
table = $('#test-scores').dataTable({
  ...
  initComplete: function() {
    setTimeout(function() {
      $(window).trigger('resize');
    })
  }
});

Answer №2

If you're already utilizing the Responsive extension of DataTable, you have the option to employ the responsivePriority feature to achieve the desired functionality. This feature will automatically determine which columns should be hidden based on the table's available space and your specified priority.

Please note: The priority is in reverse order, meaning a column with a higher priority value will be hidden before a column with a lower priority value.

$('#test-scores').dataTable({
 //...
 responsive: true,
 columns: [
 { data: "district", responsivePriority: 1 },
 { data: "school", responsivePriority: 2 },
 { data: "subject", responsivePriority: 3 },
 { data: "rate", responsivePriority: 4 },
 { data: "test_takers", responsivePriority: 5 },
 ],
 //...
});

Example

var table = $('#example').DataTable({
 responsive: true
});
<link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/responsive/2.2.3/css/responsive.dataTables.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.2.3/js/dataTables.responsive.min.js"></script>
<table id="example" class="nowrap" width="100%">
 <thead>
 <tr>
 <th data-priority="0">Seq.</th> <!-- The first column should always be visible or the collapsed data will not be visible -->
 <th data-priority="1">Name</th>
 <th data-priority="3">Position</th>
 <th data-priority="4">Office</th>
 <th data-priority="5">Start date</th>
 <th data-priority="1">Salary</th>
 </tr>
 </thead>

 <tfoot>
 <tr>
 <th>Seq.</th>
 <th>Name</th>
 <th>Position</th>
 <th>Office</th>
 <th>Start date</th>
 <th>Salary</th>
 </tr>
 </tfoot>

 <tbody>
 <tr>
 <td>2</td>
 <td>Tiger Nixon</td>
 <td>System Architect</td>
 <td>Edinburgh</td>
 <td>2011/04/25</td>
 <td>$320,800</td>
 </tr>
 <tr>
 ...
 </tbody>
</table>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting AJAX issues in Firefox with window.location.assign function

Here is my AJAX POST request that sends serialized form data to the server: // Handle form submission. $('#evaluationform').on('submit', function(e){ e.preventDefault(); ajaxObject = { url: $("#evaluationform").attr("a ...

React Native: A guide to triggering a modal or action sheet when a button tab is clicked using Wix React Native navigation

Is it possible to trigger a modal or actionsheet by clicking on a specific bottom tab in a tab-based application using wix react native v2 navigation? These are the current packages and versions I am working with: react-native : "0.59.8" react : "16.8. ...

Issue with DWR and Android web browser

I recently encountered an issue while trying to access an application through the Android browser. The application uses DWR to maintain connections with connected clients. Everything seems to be working fine, except for the fact that if there is a 2-minut ...

The behavior of Angular 4 CSS and JS changes upon refreshing the page

Every time I try to load a page with this particular script: this.router.navigateByUrl('/report-result/'+report.id); It appears that not all the CSS and JS files are being loaded properly. The bootstrap popovers don't show up, and some ele ...

What is the proper syntax for Angular 2 form element attributes?

As I was browsing through this insightful article, I came across the following snippets: <input type="search" [formControl]="seachControl"> and <input type="text" formControlName="street"> This made me ponder on the correct syntax for ...

Encountering issues when attempting to render a function within the render method in React

When attempting to render the gridWithNode function inside the render method, I encountered an error message stating: "Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant ...

Information about Doughnut chart in React using the react-chartjs-2 package

Is there a way to write text directly on a Doughnut using react-chartjs-2? Most answers I came across explain how to place text in the center of a Doughnut, but not actually on it. Here is an image for reference: ...

Develop a website using HTML and CSS for the front-end design, complemented by Java for the

I find myself at a standstill with a project I want to tackle, but unfortunately, my knowledge of modern web development, particularly full stack, is minimal. As a result, I am completely clueless on how to proceed. Here is what I am familiar with and what ...

Ways to eliminate excess space in a string using Robot Framework

My Variable : 54, 22 What I desire : 54,22 I attempted the following methods: Executing Javascript code var a = 54, 22;var x = a.split(' ').join('');return x and Executing Javascript code var a = 54, 22;var x = a.replace(/&bso ...

Merge two arrays of objects in Ramda.js based on their shared ID property

I'm working with two arrays of objects: todos: [ { id: 1, name: 'customerReport', label: 'Report sent to customer' }, { id: 2, name: 'handover', label: 'Handover (in C ...

How is it possible that my form is able to save data into the database even without any

I am considering adding a captcha process to my form and I am brainstorming some logic for it. I downloaded a login from Google, but I am confused why my form is still storing data into the database using action=' ' instead of action="register.ph ...

Place the image on the canvas

I currently have a canvas where I am able to add text layers and images from flickr. My goal is to enable users to upload an image to the canvas using the html input. For uploading images from flickr, I am using this code: $(".search form.image-search"). ...

Adjust the input values based on the child elements within the main container

Here is a series of DIVs with unique IDs: <div id="2988"> <div class="site">YaHoot.com</div> <div class="logo">/images/yahootLogo.jpg</div> //[and so on] <input type="button" value="YaHoot" onclick="javascript: ...

Slow rendering occurs with unthrottled range input, even with proper throttling applied

I'm currently seeking some general guidelines because I'm unsure where to turn for help at the moment. The issue I am facing involves an uncontrolled input[type=range] slider that performs very slowly when there are numerous steps (works fine wi ...

What causes a neighboring div to change width when a multi-line span is present?

Here is my React code: <InfoWrapper> <InfoCircle> <span>i</span> </InfoCircle> <span className="info-label"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. elit. </span> </InfoWrap ...

Communicating data transfer between two Node.js servers through the use of the Node Serial Port technology

How can I send the message "Hello world" from one nodejs server to another using node-serialport? I have confirmed that the radios connecting the two servers are properly connected as they are displaying buffer information after running my current code. ...

Passing the contents of a datatable as parameters to a PHP script

I am facing a challenge with my datatable that has two columns, "Name" and "Age". After populating the datatable using Ajax, I create a button for each row. The goal is to send the "Name" and "Age" fields of the clicked row to a PHP script, which will then ...

What is the method or variable called "afterShow" used for in FancyBox V4 and how does it differ from its counterpart in JQuery-FancyBox V3?

We previously utilized the V3 edition of Fancybox, incorporating our increaseImageClicks and increaseVideoClicks functions within its afterShow function: /* FANCYBOX OLD (https://web.archive.org/web/20210325170940/https://fancyapps.com/fancybox/3/docs/): * ...

Display the latest item using React

I've encountered a problem with displaying the last message in my pet chat application. Currently, I have to manually scroll to the bottom every time I open the chat in order to see the latest message. This scrolling behavior is not very user-friendly ...

"Transforming a simple object into an instance of a different type in JavaScript: A step-by-step guide

Having an issue storing a session on disk for local development. The application is asking for an instance of Session to be returned, not an Object function storeCallback(session) { console.log("storeCallback ", session); fs.writeFileSync(&qu ...