JSFiddle - React, Tailwind, and code Playground

by mikecmpbll

HTML

<table class="rdg-table" border="1">
  <tr>
    <th width="20%">Gender</th>
    <td width="30%">Male</td>
    <th width="20%">DOB (Age)</th>
    <td width="30%">07/02/1990 (23)</td>
  </tr>
  <tr>
    <th>Interests</th>
    <td colspan="3">
      Coding, snooker, sports betting, cooking
    </td>
  </tr>
  <tr>
    <th>Summary</th>
    <td colspan="3">Some thing that looks better full width..</td>
  </tr>
  <tr>
    <th width="20%">Ethnicity</th>
    <td width="30%">White - British</td>
    <th width="20%">Religion</th>
    <td width="30%">None</td>
  </tr>
  <tr>
    <th width="20%">First Language</th>
    <td width="30%">English</td>
    <th width="20%">English As Additional Language</th>
    <td width="30%">No</td>
  </tr>
  <tr>
    <th width="20%">Email Address</th>
    <td width="30%">[email protected]</td>
    <th width="20%">Telephone Number</th>
    <td width="30%">01234567</td>
  </tr>
</table>

CSS

table th {
    text-align: left;
}

JavaScript

(function($) {
  "use strict";

  $.fn.responsiveDataGrid = function(options) {
    return this.each(function() {
      var $this = $(this);
      var $new_table, $old_table;
      var currentSize = 99999;

      // default size below which to pack is 768
      if (!options.packAt)
        options.packAt = '768'

      if (!$this.is("table")) {
        return $this.find("table").each(function(index, item) {
          $(item).responsiveDataGrid(options);
        })
      }

      // check after the initial load
      checkForResize();

      // check subscriptions when window width changes
      $(window).resize(function () {
        checkForResize();            
      });

      // see if subscriptions need to be fired
      function checkForResize() {
        // get the screen width
        var width = $(window).width();

        if (width <= options.packAt && currentSize > options.packAt) {
          currentSize = width;
          packDataGrid();
        } else if (width > options.packAt && currentSize <= options.packAt) {
          currentSize = width;
          unpackDataGrid();
        }
      }

      function packDataGrid() {
        if (!$new_table) {
          $new_table = $this.clone().empty();
          $this.clone().find('tr').each(function(i,tr) {
            var $row = $(tr);
            $row.children('th').each(function(i,th) {
              var $th = $(th);
              var $td = $th.next();
              if ($td.is('td')) {
                var $updated = $('<tr>', {'class':'rdg-wrapped'}).append($th, $td);
                $new_table.append($updated);
              }
            });
          });
        }
        $old_table = $this.replaceWith($new_table);
      }

      function unpackDataGrid() {
        $new_table.replaceWith($old_table);
      }
    });
  }
})(jQuery);

$(function() {
    $('.rdg-table').responsiveDataGrid({});
});