Inverting Tables Responsively

Tables are notoriously difficult to handle responsively. If there is a significant difference between the number of rows and the number of columns, the ideal layout for large screen sizes uses more columns then rows, but the ideal layout for small screens uses more rows than columns. However, there is no simple way to handle that conversion with only CSS (Edit: it appears I was wrong about that. David Bushell has posted a CSS solution here: https://dbushell.com/2016/03/04/css-only-responsive-tables/).

Here is the code I used to invert the order of the table cells. This converts each column into a row, and vice versa.

// Calls the function to check table arrangement
amCheckTables();

// See: https://css-tricks.com/snippets/jquery/done-resizing-event/
resizeTimer = 0;
$(window).on('resize', function(e) {
	clearTimeout(resizeTimer);
	resizeTimer = setTimeout(function() {
		amCheckTables();
	}, 250);
});


/**
 * Checks to see if tables need to be inverted.
 */
function amCheckTables() {

	var amBreakpoint = 900;

	if ($(window).width() < amBreakpoint) {
		if ( !$('.supports-inverting').hasClass('inverted-complete') ) {
			$('.supports-inverting').addClass('inverted-complete');
			amInvertTables();
		}
	}

	if ($(window).width() > (amBreakpoint - 1)) {
		if ( $('.supports-inverting').hasClass('inverted-complete') ) {
			$('.supports-inverting').removeClass('inverted-complete');
			amInvertTables();
		}
	}
}

/**
 * Inverts tables between horizontal and vertical layouts
 * 
 * See: https://stackoverflow.com/questions/25681595/javascript-jquery-swap-horizontal-and-vertical-order-of-html-table
 */
function amInvertTables() {
	var t= document.getElementsByTagName('tbody')[0],
	r= $('.supports-inverting tr'),
	cols= r.length, rows= r[0].getElementsByTagName('td').length,
	cell, next, tem, i= 0, tbod= document.createElement('tbody');

	while(i<rows){
		cell= 0;
		tem= document.createElement('tr');
		while(cell<cols){
			next= r[cell++].getElementsByTagName('td')[0];
			tem.appendChild(next);
		}
		tbod.appendChild(tem);
		++i;
	}
	t.parentNode.replaceChild(tbod, t);
}

Just a few things to note about this code:

  1. This only applies to tables that are inside an element with the supports-inverting class. This provides control over which tables get inverted and which tables are left alone.
  2. The amBreakpoint variable sets the responsive breakpoint below which the table is inverted.

And that’s it! There are comments in the code that reference the pages where I found code that was helpful in developing this solution.

Leave a Comment

Your email address will not be published. Required fields are marked *