Plippie Plippie -4 years ago 77
CSS Question

A way to make adding and removing classes on a table faster?

I have a large table with 27 columns and between 5 to 100 rows.
I have mode switch (checkbox) that switches the view of a table from the first 5 columns (simple) to 27 columns (expert) and back.

Currently I use the following jquery method to switch between the modes:

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


If the table has a large number of rows it is getting a while before it toggles. Is there any faster way to replace classes. Or make the above code faster?

Using css gt method partly works, but 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();
}
});


The first answer of Nick seems to be the best solution:

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


Even though I tried combining the answers of Nick and Nikita it did not resulted into a noticeable increase in speed.

final solution:

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

Answer Source

First I'd use change on a checkbox, no need for .is(":checked") just use the DOM .checked property, then more importantly for performance here, use a single .toggleClass() to effectively swap the classes.

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

Something like toggling them directly may be better though, try it out:

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

You can test that version here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download