Skip to content

Instantly share code, notes, and snippets.

@bwlng
Created June 20, 2013 23:00
Show Gist options
  • Save bwlng/5827536 to your computer and use it in GitHub Desktop.
Save bwlng/5827536 to your computer and use it in GitHub Desktop.
# Responsive Tables # Create a new table from each column in an existing table and use the labels from the old table to label the new table.
$('table').each(function(table_count) {
var table = $(this); // cache table object
var headers = table.find('thead th').clone(); // Clone so original table stays intact
var labels = table.find('tbody tr td:first-child').clone(); // Clone so original table stays intact
// Number of columns to ignore
var offset_columns = 1;
var group_wrapper_class = 'mobile_table_group';
var group_wrapper_id = group_wrapper_class + '_' + table_count;
var table_wrapper_class = 'mobile_table_wrapper';
var table_wrapper_styles = 'float: left; margin-left: 20px';
$(table).after('<div class="'+ group_wrapper_class +'" id="'+ group_wrapper_id +'"></div>');
headers.each(function(column_count) {
// Skip offset columns
if (column_count >= offset_columns) {
// Get the text from each header cell to title the table
var title = $(this).text();
// Create a new table for each header cell
var new_table = $(
'<div class="'+ table_wrapper_class +'" style="'+ table_wrapper_styles +'">' +
'<h1>' + title + '</h1>' +
'<table class="generated_for_mobile">' +
' <tbody>' +
' </tbody>' +
'</table>' +
'</div>'
);
// Cache tbody where we'll be adding rows for each row from the desktop table
var new_table_body = new_table.find('tbody');
labels.each(function(label_count) {
// Use the label for each row from the table
var row_label = $(this).text();
// Get the content for the corressponding row to each label
var row_content = table.find('tbody tr:eq('+ label_count +') td:eq('+ column_count +')').text();
// Create a new row with the label and content
$(new_table_body).append(
'<tr>' +
'<td>' + row_label + '</td>' +
'<td>' + row_content +'</td>' +
'</tr>'
);
label_count++
});
// Append each table to wrapper div
$('#' + group_wrapper_id).append(new_table);
}
column_count++
});
table_count++
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment