Is there a faster method for adding and removing classes on a table?

I have a sizeable table containing 27 columns and anywhere from 5 to 100 rows. To switch between a simple view showing the first 5 columns and an expert view showing all 27 columns, I have implemented a mode switch (checkbox).

Currently, I am using the following jQuery method to facilitate the mode switch:

 $("#ToggleTableCells").click(function(){
    if($(this).is(':checked')){
            $(".hiddencells").removeClass("hiddencells").addClass("showcells");
            }else{
            $(".showcells").removeClass("showcells").addClass("hiddencells");
    }
});

However, toggling the modes in a table with a large number of rows is taking longer than desired. Is there a quicker way to replace classes or optimize the provided code?

While the css gt method partially works, toggling back hides all table rows:

$("#toggleTableCells").change(function() {  
                if(this.checked){                   
                $("#Table tr td:gt(4), #Table tr th:gt(4)").show();             
                }else{                      
                $("#Table tr td:gt(4), #Table tr th:gt(4)").hide(); 
                }
    });

It appears that the first solution offered by Nick is the most effective:

$("#ToggleTableCells").change(function(){
    if(this.checked){
        $(".hiddencells").toggleClass("hiddencells showcells");
    }else{
        $(".showcells").toggleClass("showcells hiddencells");
    }
});

Experimenting with a combination of Nick and Nikita's solutions did not yield a significant speed enhancement.

As a final solution, I have implemented the following:

var cells = $();
$("#Table tr").each(function() { cells = cells.add($(this).children(":gt(4)")); });
$("#ToggleTableCells").change(function(){
cells.toggle(this.checked);
});

Answer №1

Instead of using change on a checkbox, you can utilize the DOM .checked property to toggle the checkbox state without the need for .is(":checked"). To improve performance, consider using a single .toggleClass() to swap classes efficiently.

$("#ToggleTableCells").change(function(){
  if(this.checked){
    $(".hiddencells").toggleClass("hiddencells showcells");
  }else{
    $(".showcells").toggleClass("showcells hiddencells");
  }
});

You may also directly toggle the cells for a more efficient approach:

var cells = $();
$("#myTable tr").each(function() { cells = cells.add($(this).children().slice(5)); });
$("#ToggleTableCells").change(function(){ cells.toggle(this.checked); });​

Feel free to test out this version.

Answer №2

A quick way to increase the speed of your code is to make your class selectors more targeted. For example, instead of using

("#my_table td.hiddencells")

consider using

$(".hiddencells")

for better performance. This jQuery optimization technique involves using specific selectors rather than general ones.

Answer №3

I found a solution using checkbox toggling for hiding and showing table cells with the class "hiddencolumn".

$("checkbox").change(function() {
    if (this.checked) {
      $(".hiddencolumn").show();
    } else {
      $(".hiddencolumn").hide();
    }
});

This method is efficient even with a large dataset of 500 rows. The performance is impressive.

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

Storing JSONP data in a variable: Tips and Tricks

Having an issue with storing JSONP data into variables and using it as input for a Google Pie Chart. Consider the following: Data in test.json: { "name": "ProjA", sp": 10, "current": 20 } The goal is to retrieve the SP value. Attempted solution usin ...

implement css property solely when device is in landscape orientation

I am facing an issue with applying CSS to a mobile device, specifically for horizontal orientation. When the device is in a vertical position, the page appears blank, and different CSS loads for desktop view. Although I have managed to make the desktop CS ...

What could be causing the issue of my navbar text not changing color using CSS?

Despite several attempts, I am unable to change the color of the hyperlinks in blue or purple using the HTML and CSS below. Can anyone point out what I might be missing? nav ul { /* Navbar unordered */ list-style: none; text-align: center; backgr ...

incorporating a rollover menu into the images displayed on the webpage

I have a set of 3 images displayed inline, each enclosed in a span tag with the class imgAvatar. Positioned above them are 3 identical hidden images (delete buttons) stored within spans with the class imgAvatarSelector. The CSS for the delete buttons is a ...

tap into adhesive, translucent screen

I designed a webpage with an iframe at the bottom that I set to be transparent so that overlapped elements are visible. However, I encountered an issue where the links beneath the iframe were not clickable unless I disabled pointer-events for the iframe. ...

Utilize various CSS styles for text wrapping

I'm struggling to figure out where to begin with this problem. My goal is to create a three-column row that can wrap below each other if they cannot fit horizontally. The height of the row should adjust to accommodate the items while maintaining a fix ...

Is there a way to modify certain parameters of a plugin without the need to directly edit the

Is there a way to modify certain parameters of a plugin without directly editing it? You can find the link to the plugin here: . Can we include an additional script to override specific parameters of the above script, such as setting displayTime to 1000 ...

What are the steps for creating a JSON array in JavaScript?

Hello, I'm facing an issue with the following code: javascript var cadena="["; $('.box').each(function(){ var clase=$(this).attr("class"); var id_t=$(this).attr("id"); if(clase=="box ...

Tips for organizing an array with specific conditions

I need help sorting an array in PHP based on certain conditions. Below is the sample array: $array = [ [ "a" => 4, "b" => 8, "c" => 1 ], [ "a" => 9, "b" => 4, "c" => 0 ], [ "a" => -9, "b" => -4, "c" => 1 ], ]; ...

Automatically align a Div to the right within an ngFor directive in an Angular 6 application

<div class="row"> <div class="col-lg-4 col-xs-6" *ngFor="let client of clients;index as i"> <!-- small box --> <div class="small-box bg-dashboard-box" > <div class="inner"> <div class="text-black"> ...

What is the best way to include a final tag on its own line?

I'm trying to add a new line for "Payment Remaining", but it doesn't go to the next line as expected. I need the final text to be on a separate line, Payment Remaining #authorization-wizard-start-work .btn-group label.active { color: #009 ...

Is it possible to resize a div based on the width of the window?

Imagine a scenario where it's not possible to change the content of a div, but only its shape and size by using transform: scale(1.4) for instance. To better understand this concept, take a look at This Website and try resizing the window using brows ...

What is the reason border property does not transition effectively?

I am trying to remove the border property after a certain period of time (1 second) and make it smooth. Here is what I have attempted: var elem = $('div').css({'border-top':'6px solid #FC9A24', 'border-le ...

Material UI Card shadow effect getting cropped

Currently experiencing an uncommon issue while using Material UI's Card component - the box-shadow is cut off on the top and bottom sides. Any suggestions on how to resolve this problem? Check out my code below: import React, { Component } from & ...

JSON Compression/Decompression Utility

Looking for a solution to handle large data sets in a .NET Web Method (C#) that accepts JSON objects generated by JQuery on the client side using Ajax. The current process is functional, but there is concern about handling potentially very large amounts o ...

The Bootstrap modal fails to open

I am currently working on implementing a Navbar button that triggers a Bootstrap modal containing a form. While looking for resources, I stumbled upon a useful script at https://gist.github.com/havvg/3226804. I'm in the process of customizing it to su ...

Is there a way to position the Bootstrap navbar menu items in the center specifically for mobile devices?

I have a navbar that I want to center the menu li items when it collapses. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b9dbd6d6cdcacdcbd8c9f98c978b978b">[ema ...

Use .empty() method to remove all contents from the tbody element after creating a table

Currently, I am working on a project where I am creating a drop-down list to assist users in selecting media and ink for their printers. The goal is to then generate a table displaying the selected results. While I have managed to successfully generate the ...

What steps are involved in creating a mobile web app using Visual Studio 2012, jQuery, and ASP.NET MVC?

As a beginner in asp.net, I am tasked with creating a mobile web app project. Before diving into development, I would like to first focus on designing my app. Can anyone provide guidance on how I can achieve this? Any help is appreciated. ...

Is there a way for me to determine which class has been selected using jQuery and JavaScript?

I created a list containing various links: <li class="link-1"><a href="#">One</a></li> <li class="link-2"><a href="#">Two</a></li> <li class="link-3"><a href="#">Three</a></li> .. Wh ...