Last Updated: February 25, 2016
·
2.876K
· richthegeek

A better scrolling-tables plugin

Today I needed to display a table that could have anywhere between 0 and a few hundred columns... and do it in a way that kept the "primary key" visible.

I took Zurbs responsive tables experiment as a base and switched it around to perform it's magic when the table was wider than it's parent (keeping it responsive), to allow the "primary" column to be switched, and to play nicely with the mousewheel.

Here's the JS for it:

jQuery(document).ready(function($) {
  var switched = false;
  var updateTables = function() {
    $("table.responsive").each(function(i, element) {
      if ($(element).width() > $(this).parent().width()) {
        splitTable($(element));

        $(element).find('th').click(function() {
          index = $(this).parent().children().index(this);

          $(this).parents('table').find('tr').each(function() {
            $(this).children().eq(index).prependTo($(this));
          });

          unsplitTable($(element));
          splitTable($(element));
        });
      }
    }).bind('DOMMouseScroll mousewheel', function(e) {
      if (e.originalEvent && e.originalEvent.wheelDeltaY) {
        p = $(this).parent();
        p.scrollLeft(p.scrollLeft() + (-1 * e.originalEvent.wheelDeltaY));
      }
    });
  };

  $(window).load(updateTables);
  $(window).bind("resize", updateTables);
  $(window).bind('updateTables', updateTables);

    function splitTable(original)
    {
        original.wrap("<div class='table-wrapper' />");

        var copy = original.clone();
        copy.find("td:not(:first-child), th:not(:first-child)").css("display", "none");
        copy.removeClass("responsive");

        original.closest(".table-wrapper").append(copy);
        copy.wrap("<div class='pinned' />");
        original.wrap("<div class='scrollable' />");
    }

    function unsplitTable(original) {
    original.closest(".table-wrapper").find(".pinned").remove();
    original.unwrap();
    original.unwrap();
    }
});

.
And the SCSS:

 .pinned {
    position: absolute;
    left: 0;
    top: 0;
    background: #fff;
    overflow: hidden;
    border-right: 1px solid #ccc;
    border-left: 1px solid #ccc;

    table {
        border-right: none;
        border-left: none;
        width: 100%;
        th, td {
            white-space: nowrap;
            font-weight: bold;
        }
    }

    td:last-child {
        border-bottom: 0;
    }
}

div.table-wrapper {
    position: relative;
    overflow: hidden;
    margin-bottom: 20px;
    border-right: 1px solid #ccc;

    div.scrollable {
        overflow: scroll;
        overflow-y: hidden;
    }
}
table.responsive {
    margin-bottom: 0;

    td, th {
        position: relative;
        overflow: hidden;
        white-space: nowrap;

        &:hover {
            overflow: visible;
        }
    }
}

The original: http://www.zurb.com/playground/playground/responsive-tables/index.html