A quick way to align row heights in two different tables

This javascript function is currently used to align all rows by matching their heights in 2 different tables. Each table has more than 1000 rows. And it takes more than 4 seconds to complete this function. Is there a faster way to match row heights of two different tables? Thanks

function alignTableRowHeights() { $('#table1 tr').each(function(i) { var rowDisplay=$(this).css("display") if(rowDisplay!="none"){ // Row is visible var tableTwoRow = $('#table2 tr').get(i); var height = $(tableTwoRow).height(); $(this).height(height); } }); } 

Rows in the table do not have the same height. Therefore, there must be logic to get the height of each row individually. And some lines can be hidden (for expansion and smoothing), and therefore it is necessary to check whether the line is displayed or not. The goal is to display the two tables side by side so that the visible rows remain in sync and aligned.

+4
source share
2 answers

Javascript will be the fastest, however the slowest part is probably not jQuery itself, but how you use it:

  • For each row, you request for all other rows only its use. Decision. Get the query results before the loop for this table.
  • For each row, you request the retrieval of the display attribute from the computed styles. Solution: use the jQuery :visible selector, so you don't need to do a separate check.
  • Sometimes manipulating the DOM while the table is visible can be very slow depending on your layout, styles, etc. Solution: delete the table you are updating from dom, update the heights, then return it.

Here's how I can do it:

 function alignTableRowHeights() { // copy the heights into an array var heights = []; $('#table2').find('tr:visible').each(function(i) { heights[i] = $(this).height(); }); // get visible table one rows before we remove it from the dom var tableOneRows = $('#table1').find('tr:visible'); // remove table one from the dom var tempDiv = $('<div />'); var table1 = $('#table1'); table1.replaceWith(tempDiv); $.each(tableOneRows, function(i) { $(this).height(heights[i]); }); // put table one back in the dom tempDiv.replaceWith(table1); } 
+2
source

Hide the table until the height is corrected:

 function alignTableRowHeights () { $('#table1').css('display', 'none'); $('#table1 tr').each(function (i) { var rowDisplay = $(this).css("display") if (rowDisplay != "none") { // Row is visible var tableTwoRow = $('#table2 tr').get(i); var height = $(tableTwoRow).height(); $(this).height(height); } }); $('#table1').css('display', ''); } 

Live demo in jsFiddle .

0
source

Source: https://habr.com/ru/post/1501237/


All Articles