responsive-tables.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. $(document).ready(function() {
  2. var switched = false;
  3. var updateTables = function() {
  4. if (($(window).width() < 767) && !switched ){
  5. switched = true;
  6. $("table.responsive").each(function(i, element) {
  7. splitTable($(element));
  8. });
  9. return true;
  10. }
  11. else if (switched && ($(window).width() > 767)) {
  12. switched = false;
  13. $("table.responsive").each(function(i, element) {
  14. unsplitTable($(element));
  15. });
  16. }
  17. };
  18. $(window).load(updateTables);
  19. $(window).on("redraw",function(){switched=false;updateTables();}); // An event to listen for
  20. $(window).on("resize", updateTables);
  21. function splitTable(original)
  22. {
  23. original.wrap("<div class='table-wrapper' />");
  24. var copy = original.clone();
  25. copy.find("td:not(:first-child), th:not(:first-child)").css("display", "none");
  26. copy.removeClass("responsive");
  27. original.closest(".table-wrapper").append(copy);
  28. copy.wrap("<div class='pinned' />");
  29. original.wrap("<div class='scrollable' />");
  30. setCellHeights(original, copy);
  31. }
  32. function unsplitTable(original) {
  33. original.closest(".table-wrapper").find(".pinned").remove();
  34. original.unwrap();
  35. original.unwrap();
  36. }
  37. function setCellHeights(original, copy) {
  38. var tr = original.find('tr'),
  39. tr_copy = copy.find('tr'),
  40. heights = [];
  41. tr.each(function (index) {
  42. var self = $(this),
  43. tx = self.find('th, td');
  44. tx.each(function () {
  45. var height = $(this).outerHeight(true);
  46. heights[index] = heights[index] || 0;
  47. if (height > heights[index]) heights[index] = height;
  48. });
  49. });
  50. tr_copy.each(function (index) {
  51. $(this).height(heights[index]);
  52. });
  53. }
  54. });