Concealing table columns using JavaScript - adapt layout on the fly

I am currently implementing a responsive design feature on my website, where I need to hide certain columns of a table when the viewport size decreases beyond a specific point. Initially, I tried using .style.visibility = "collapse" for all <tr> elements and .style.opacity = "0" for all <td> elements. Additionally, I had to manipulate the table's background to ensure that the width of the table expands by 160% so that the remaining columns fill the screen.

While this method works fine on Chrome, Firefox, IE (including ie8!), and mobile browsers, it feels like a bit of a workaround. Are there any other more efficient solutions for achieving this?


    var jmq = window.matchMedia("screen and (max-width: 610px)");
    jmq.addListener(jmqListener);

    function jmqListener(jmq){
        var colTitle = getElementsByClassName('col-title');
        var colName = getElementsByClassName('col-name');
        var colDate = getElementsByClassName('col-date');
        var colFb = getElementsByClassName('col-fb');
        var table = getElementsByClassName('default');

        if (jmq.matches || window.innerWidth < 611 ) {
            //Mobile view
            ... resize controls
            // hide specified table columns
            if (colName !== null){
                for(var i=0,j=colName.length; i<j; i++){
                    colName[i].style.visibility = "collapse";
                    colName[i].style.opacity = "0";
                }
            }
            // Workaround - increase table width and hide background to prevent showing reserved space 
            if (table !== null){
                for(var i=0,j=table.length; i<j; i++){
                    table[i].style.width = "160%";
                    table[i].style.background = "transparent";
                }
            }
        } else {
            // Desktop view
            ... restore control layout for desktop
            // show hidden table column(s)
            if (colName !== null){
                for(var i=0,j=colName.length; i<j; i++){
                    colName[i].style.visibility = "visible";
                    colName[i].style.opacity = "100";
                }
            }
            if (table !== null){
                for(var i=0,j=table.length; i<j; i++){
                    table[i].style.width = "100%";
                    table[i].style.background = "#C8C8C8";
                }
            }
        }    
    }

function getElementsByClassName(className) {
    if (document.getElementsByClassName) { 
        return document.getElementsByClassName(className); 
    } else { 
        return document.querySelectorAll('.' + className); 
    } 
}

Answer №1

Consider optimizing your for loop in this way:

for(var i=0; i<colName.length; i++){
    colName[i].style.display = "none";
}

It's worth noting that the j variable is unnecessary.

According to the MDN documentation, the collapse value of visibility results in hiding table rows and columns while maintaining space for them, without affecting other elements' sizes.

By using display: none, you effectively achieve the same result as described above.

Answer №2

Consider implementing CSS3 Media Queries for responsive design.

For example, you can use the following code snippet:

@media all and (max-width: 700px) {
table, tr, td {
    display: none;
}

When the viewport width of your device is 700px or less, the display: none; property will be applied to hide elements like tables, table rows, and table cells.

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

Error encountered: Failure to locate Yii2 class during an Ajax request

I've created a model class that represents a table in my database: <?php namespace app\models; use yii\db\ActiveRecord; class Pricing extends ActiveRecord { } Next, I attempted to utilize a simple PHP function in a separate fil ...

Guide to utilizing jquery within node.js

Can anyone assist me with using jQuery in Node.js? I have the following code: const jsdom = require("jsdom"); const { JSDOM } = jsdom; const { window } = new JSDOM('<!DOCTYPE html>'); const $ = require('jquery')(window); var con ...

Is there a way to integrate Javascript code with a React component?

I need to find a way to include this block of code in just one specific React component. Any suggestions? <!-- Create a button that your customers click to complete their purchase. Customize the styling to suit your branding. --> <button sty ...

Grunt is designed to generate a single file, instead of producing multiple files

I have a simple Gruntfile that is designed to read a plain text file line by line and create an html file of the same name for each line. However, it seems to only work with one line in the file at a time, not multiple lines. Here is the console output wh ...

PHP and JavaScript both offer methods for escaping variables that are written in the syntax ${HOST}

How can I safely handle variables from the database like ${HOST}? This issue arises when code is posted within <pre><code> tags. If left as it is, an error occurs: Uncaught ReferenceError: HOST is not defined. In this specific context, usin ...

Encountering a "variable not found" error when trying to run the JavaScript code to manipulate the web element

Upon executing the command to change the value of a web element text, I encountered an error stating "Can't find variable: e." sel=webdriver.PhantomJS() sel.get=('http://stackoverflow.com/questions?pagesize=50&sort=newest') elements=sel ...

JavaScript will continue to run uninterrupted even after refreshing the webpage

Has anyone else encountered the issue of a javascript on a page continuing to run even after the page is refreshed? From what I understand, javascript is single-threaded and should stop running when the page is refreshed. Just to provide some background, ...

I am facing an issue with Angular where the $http.get method is

It seems like there must be a small oversight causing this apparently simple problem. I have a function that interacts with the Spotify API to search for an artist. I know that by accessing the corresponding route using a standard URL, a result is returne ...

React Express Error: Unable to access property 'then' of undefined

I'm facing an issue while trying to server-side render my react app for users who have disabled JavaScript and also for better search engine optimization. However, I am encountering the following error: TypeError: Cannot read property 'then' ...

What is the best way to save only the time in MySQL using Sequelize?

How can I properly store the Time HH:MM:SS using sequelize without encountering errors? I've tried using Time as a String and also as a Date Object, but I'm still facing issues. Here is the function I am using: const dateCollection = await booki ...

What is the correct method in CSS to resize an image while maintaining its proportions within a div container?

I've been struggling to properly insert images into a <div> element on my website. I've experimented with various techniques, such as setting max-width and max-height to 100%, changing the display property of the parent element to flex, and ...

Creating a NgFor loop in Angular 8 to display a dropdown menu styled using Material

I'm currently facing an issue with incorporating a Materialize dropdown within a dynamically generated table using *ngFor. The dropdown does not display when placed inside the table, however, it works perfectly fine when placed outside. <p>User ...

What is the best way to organize an array both alphabetically and by the length of its elements?

Imagine I am working with an array like this: ['a', 'c', 'bb', 'aaa', 'bbb', 'aa']. My goal is to sort it in the following order: aaa, aa, a, bbb, bb, c. this.array= this.array.sort((n1, n2) => ...

Venom Bot encounters issue with sending files, displaying "Error processing files" message

When attempting to send a PDF in the code snippet below, I encountered the following error: app.post('/send-pdf',[ body('number').notEmpty(), ], async (req, res) => { const errors = validationResult(req).formatWith(({ msg }) =&g ...

Ajax handling all tasks except for adding HTML elements

Having an issue with my basic "Load More on Scroll" AJAX function. The console is showing that the HTML is being sent back from the request, but for some reason, nothing is being rendered on the page. I must be missing something really simple here. $(wi ...

What is the best method for transmitting the filename using Plupload?

I've been trying to solve this issue for a while now. My problem seems straightforward – I want to send the filename along with the file as a multipart request in Plupload, but so far, I haven't had any success. The main thing I'm missin ...

Ways to change the URL post saving a cookie with express?

I have written this code for user login in my Express router: if (password === realpassword) { res.cookie('thecookie', 'somethingliketoken'); res.redirect(302, '/somepages'); } else { res.status(403).end(); } The ...

Personalized search feature for Bootstrap tables

Below is the table structure: <table> <tr> <th>Number</th> <th>Name</th> </tr> <tr> <td>200.10.1234</td> <td>Maria Anders</td> </tr> <tr> < ...

Is the Bootstrap datatable failing to be responsive in the tabler dashboard when viewed on mobile devices?

Implemented Bootstrap Datatable to display database data on a tabler admin dashboard. The functionality works perfectly on desktop view, but encounters issues on mobile devices. Any suggestions on how to resolve this problem? Desktop View Screenshot: ht ...

Tips for creating a Vuex mutation without using asynchronous promises

I have a project underway that involves building an app using Vue.js, Vuex, and Firebase to update data from Firestore database to the state in mutations. Even though mutations are synchronous and promises (.then) are asynchronous, my current implementat ...