Fluid table

by Bjørn Tennøe

HTML

<table class="fluid-table">
  <tr>
    <td>Avail&shy;able <i>until</i>:</td><td>No&nbsp;expiry date</td><td>Avail&shy;ability:</td><td>Worldwide</td><td></td>
  </tr><tr>
    <td>Year:</td><td>2016</td><td>Length:</td><td>29&nbsp;minutes</td><td></td>
  </tr><tr>
    <td>First broad&shy;cast:</td><td>Feb&nbsp;2</td><td>Last broad&shy;cast:</td><td>Feb&nbsp;3</td><td></td>
  </tr>
</table>

CSS

.fluid-table td {
  /*vertical-align: top;*/
  padding-right: 5px;
}

.fluid-table td:nth-child(odd) {
  color: rgb(119, 119, 119);  
}

.fluid-table-visible-target td>i {
  font-style: inherit;
  white-space: nowrap;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* .fluid-table-invisible-source must be slighly more padded than .fluid-table-visible-target due to IE bug */

.fluid-table-invisible-source td:nth-child(even) {
  color: rgb(30, 30, 30);  
  padding-right: 10px;
}

.fluid-table-visible-target td:nth-child(even) {
  color: rgb(30, 30, 30);  
  padding-right: 9px;
}

JavaScript

// Resize fluid table(s)
function resizeFluidTables() {

  // Show source cells
  $( ".fluid-table-invisible-source" ).show(0);

  var fluidTableCellWidth = [];

  // Measure (normally invisible) source cells
  $( ".fluid-table-invisible-source td" ).each(function( index, value ) {
    fluidTableCellWidth[index] = $( this ).width();
  });

  // Resize (always visible) target cells. Adding 1 pixel due to apparent bug in Firefox.
  $( ".fluid-table-visible-target td>i" ).each(function( index, value ) {
    $( this ).css({'width': fluidTableCellWidth[index]+1 });
  });

  // Re-hide source cells
  $( ".fluid-table-invisible-source" ).hide();

}

// Create table(s) to be fluid
function initFluidTables() {

  // Create a container. Not really necessary, but keeps DOM tidier.
  $(".fluid-table").wrap( "<div></div>" );

  // This looks like a mess. What it does, is that .fluid-table duplicates itself, and each sibling gets a different class.
  $(".fluid-table").each(function() {
    $( this ).clone().appendTo( $( this ).addClass( "fluid-table-invisible-source" ).parent() ).addClass( "fluid-table-visible-target" );
  });

  // Add truncating element inside target cells
  $(".fluid-table-visible-target td").wrapInner( "<i></i>");

  // Truncate table contents at first drawing of the DOM and every time the window resizes
  resizeFluidTables();
  $( window ).resize(function() {
    resizeFluidTables();
  });
}

initFluidTables();