Dynamic table using jQuery
by ajinkya_parakh
HTML
<table border="1">
<thead>
<tr>
<th>Lonnnnnng Header 1 <span><b>-</b></span></th>
<th>Lonnnnnng Header 2 <span><b>-</b></span></th>
<th>Lonnnnnng Header 3 <span><b>-</b></span></th>
</tr>
</thead>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
<td>row 1, cell 3</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
<td>row 2, cell 3</td>
</tr>
<tr>
<td>row 3, cell 1</td>
<td>row 3, cell 2</td>
<td>row 3, cell 3</td>
</tr>
<tr>
<td>row 4, cell 1</td>
<td>row 4, cell 2</td>
<td>row 4, cell 3</td>
</tr>
</table>
CSS
body { font-family: Sans-Serif; }
table {
border: solid 1px #888;
table-layout:fixed;
word-wrap:break-word;
}
table thead { background-color: #6E6E6E; color: #fff; }
table td, table th { padding: 5px; }
.alt { background-color: #ddd; }
.hover { background-color: #81DAF5; }
JavaScript
$(function() {
$('table tbody tr:odd').addClass('alt');
$('table tbody tr').hover(function() {
$(this).addClass('hover');
}, function() {
$(this).removeClass('hover');
});
});
$('tr th').click(function() {
var collapse_width = '49px';
// alert($(this).css('width'));
if ($(this).css('width') == collapse_width) {
$(this).attr('nowrap', 'nowrap');
$(this).find('span').html('<b>-</b>');
}
else {
$(this).removeAttr('nowrap');
$(this).find('span').html('<b>+</b>');
$(this).css('width', collapse_width);
}
});