Skip to content

Instantly share code, notes, and snippets.

@applehat
Last active May 9, 2016 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save applehat/076de122ffc493d8b84d2336e231b96f to your computer and use it in GitHub Desktop.
Save applehat/076de122ffc493d8b84d2336e231b96f to your computer and use it in GitHub Desktop.
Crush tables that won't get out of the way of themselves.

TableCrusher

This code will crush tables that refuse to collapse small enough to fit their parents.

It will break tables that have a fixed width if that table ever becomes larger then its parent, tho.

It could probably be better, but whatever.

$(function(){
$("<style type='text/css'> .crushedTable { table-layout:fixed } .crushMe { text-overflow: ellipsis; white-space: nowrap; overflow: hidden; padding: 0 !important; } </style>").appendTo("head");
tableCrusher(); // run first thing, because we dont need a resize to be broken.
var tableCrusherRTime;
var tableCrushertableCrusherTimeout = false;
var tableCrusherDelta = 200;
$(window).resize(function() {
tableCrusherRTime = new Date();
if (tableCrusherTimeout === false) {
tableCrusherTimeout = true;
settableCrusherTimeout(tableCrusherResizeEnd, tableCrusherDelta);
}
});
function tableCrusherResizeEnd() {
if (new Date() - tableCrusherRTime < tableCrusherDelta) {
settableCrusherTimeout(tableCrusherResizeEnd, tableCrusherDelta);
} else {
tableCrusherTimeout = false;
tableCrusher();
}
}
function tableCrusher() {
$('table').each(function(){
var parent = $(this).parent();
var self = $(this);
if (self.width() > parent.width()) {
var colCount = 0;
self.find('tr:nth-child(1)').first().find('td, th').each(function () {
if ($(this).attr('colspan')) {
colCount += +$(this).attr('colspan');
} else {
colCount++;
}
});
var max = Math.floor(parent.width() / colCount);
self.addClass('crushedTable');
self.find('td, th').each(function(){
$(this).width(max).addClass('crushMe');
});
self.width(parent.width()-2).addClass('crushedTable');
} else {
self.find('td, th').each(function(){
$(this).removeClass('crushMe').css('width','');
});
self.removeClass('crushedTable').css('width',);
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment