Tables - duplicate widths
Passing column widths to unrelated elements for constructing scrollable tables.
by Chris Ball
HTML
<div id="new">
<div id="newfloat"></div>
</div>
<table id="old">
<thead id="oldHead">
<tr>
<th>Name</th>
<th>This is a box</th>
<th>Third</th>
<th>Last</th>
</tr>
</thead>
<tbody id="oldBody">
<tr>
<td class="first">Name goes here</td>
<td class="second"><input class="box"/></td>
<td>SHORT</td>
<td>LOOOOOOOONG</td>
</tr>
<tr>
<td class="first">Comparatively long name goes here with relative ease</td>
<td class="second"><input class="box"/></td>
<td>MEDIUMISH</td>
<td>SHORT</td>
</tr>
<tr>
<td class="first">Name goes here</td>
<td class="second"><input class="box"/></td>
<td>SHORT</td>
<td>LOOOOOOOONG</td>
</tr>
<tr>
<td class="first">Comparatively long name goes here with relative ease</td>
<td class="second"><input class="box"/></td>
<td>MEDIUMISH</td>
<td>SHORT</td>
</tr>
<tr>
<td class="first">Name goes here</td>
<td class="second"><input class="box"/></td>
<td>SHORT</td>
<td>LOOOOOOOONG</td>
</tr>
<tr>
<td class="first">Comparatively long name goes here with relative ease</td>
<td class="second"><input class="box"/></td>
<td>MEDIUMISH</td>
<td>SHORT</td>
</tr>
<tr>
<td class="first">Name goes here</td>
<td class="second"><input class="box"/></td>
<td>SHORT</td>
<td>LOOOOOOOONG</td>
</tr>
</tbody>
</table>
<a href="#" id="switch">SWITCH</a>
CSS
body {
font-family:'Arial';
font-size:10px;
width:100%;
background:#DDD;
}
#oldBody{
/*overflow-y:scroll;*/
}
#new {
background:#000;
color:#FFF;
width:100%;
border-bottom:2px solid #FFF;
position:fixed;
}
#new span {
display:inline-block;
font-weight:bold;
padding:11px 10px;
}
#newfloat {
float:right;
}
tr {
border-bottom:2px solid #FFF;
}
th {
white-space:nowrap; /* Keep headings on 1 line */
font-weight:bold;
padding:10px 10px;
}
td {
padding:5px 10px;
text-align:right;
}
td.first {
text-align:left;
width:100%;
}
td.second {
text-align:center;
}
.box {
height:30px;
width:30px;
background:#BBB;
margin:0 auto;
border:none;
}
JavaScript
function duplicate(){
// Insert widths of each td (except first), in last tr, into "w" array
var w = $('#old').find('tr:last').find('td').map(function(index){
return $(this).outerWidth();
}).get();
// Store heading text in "newth" array
var newth = $('#oldHead').find('th').map(function(){
return $(this).text();
}).get();
// Append stored text array to new table
for (var i = 0; i < newth.length; i++){
if (i<1){
$('<span>' + newth[i] + '</span>').appendTo('#new');
} else {
$('<span style="width:' + (w[i] - 20) + 'px">' + newth[i] + '</span>').appendTo('#new > #newfloat');
}
}
// Remove original headings
// $('#oldHead').find('tr').remove();
$('#oldBody').find('tr:first').find('td').each(function(index){
if (index === 1){
$(this).css({'min-width': w[index] - 20 + 'px'});
} else {
$(this).css({'width': w[index] + 'px'});
}
});
}
$('#switch').click(function(){
duplicate();
});