Code!

Code Snippet: Responsive Tables (Javascript)

A code snippet for responsive tables, designed to progressively enhance semantic html tables with Javascript.

Based on the approach from http://codepen.io/anon/pen/QwPVNW

Javascript

function responsiveTables(dirty) {
	// Do you want to force using titles and just hope that the table is set up with a header in the first row?
	// You probably don't but the option is there.
	if(!dirty) {dirty = false;}

	$('table').each(function() {

		//Already done? skip.
		if($(this).find('[data-label]').length) {
			return true;
		}

		var $headCells = $(this).find('th, thead td');
		var $rows = $(this).find('tbody tr');

		//If we have some headers:
		if($headCells.length) {
			$rows.each(function(i) {

				// skip any rows with headers
				// skip any tables where header numbers don't match row numbers
				if($(this).find('th').length || $headCells.length != $(this).find('td').length) {
					return true;
				}
		
				//add data-label to body cells
				$(this).find('td').each(function(j) {
					$(this).attr('data-label', $headCells.eq(j).text());
				});
			});

		// No headers in table? We can just use the first row and home that they're headers.
		} else if(dirty) {
			$dirtyHeadCells = $(this).find('tr:first td');
			$rows.each(function(i) {

				//add data-label to body cells
				$(this).find('td').each(function(j) {
					$(this).attr('data-label', $dirtyHeadCells.eq(j).text());
				});
			});

		}
	});
}

Sass

@media screen and (max-width: 767px)
	#top table 
		th, thead
			display: none
		tr
			display: block
		td, td p
			display: block
			text-align: right
			
		td:before
			content: attr(data-label)
			float: left
			text-transform: uppercase
			font-weight: bold

Thanks for stopping by.

Twitter
@tweetbollig
Subscribe via RSS
subscribe
Email
Skype call or chat
chat
Go to top