[jQuery] RWD Responsive Table
Table switching to accordion on small screensizes.
by Burkhard GS
HTML
<div class="js-responsive-table">
<table>
<tr>
<th>Kurse</th>
<th>Wo?</th>
<th>Was?</th>
<th>Wann?</th>
<th>Zusatz</th>
</tr>
<tr>
<td>Testkurs </td>
<td>Am Ort</td>
<td>Kurze Beschreibung</td>
<td>Uhrzeit</td>
<td>Uhrzeit (MItteleuropäisch)</td>
</tr>
<tr>
<td>Beispielkurs</td>
<td>Platz</td>
<td>Folgende Inhalte</td>
<td>Zeitpunkt</td>
<td>Zeitpunkt (in Worten)</td>
</tr>
</table>
</div>
CSS
.js-responsive-table {
margin-bottom: 1em;
font: normal 1em/1.4 sans-serif;
color: #666;
}
.js-responsive-table th, .js-responsive-table td {
padding: 20px 10px;
color: #6e6e6e;
}
.js-responsive-table tr {
border-bottom: 1px solid #ddd;
}
.js-responsive-table th {
background: #eee;
}
.js-responsive-table th, .js-responsive-table tr:first-child td {
font-weight: bold;
}
.js-responsive-table .icon-accordion {
display: none;
}
.js-responsive-table td h3 {
margin: 0;
padding: 0 0 5px 0;
display: none;
font-weight: bold;
}
@media (max-width: 680px) {
.js-responsive-table table, .js-responsive-table tbody, .js-responsive-table table tr, .js-responsive-table table td, .js-responsive-table table th {
display: block;
width: 100%;
}
.js-responsive-table table tr {
max-height: 60px;
overflow: hidden;
position: relative;
cursor: pointer;
}
.js-responsive-table .icon-accordion {
display: block;
text-align: center;
width: 16px;
height: 16px;
position: absolute;
right: 15px;
top: 15px;
font-style: normal;
font-size: 1.6em;
}
.js-responsive-table td h3 {
display: block;
}
}
JavaScript
/**
* Responsive HTML Table
*
* @desc RWD: HTML table turns into an accordion.
* @author [HZ]
* @dependency jQuery
*/
$.fn.responsiveTable = function () {
$(this).find('table').each(function () {
var trAcc = $(this).find('tr').not('tr:first-child'),
thHead = [];
$(this).find('tr:first-child td, tr:first-child th').each(function () {
headLines = $(this).text();
thHead.push(headLines);
});
trAcc.each(function () {
for (i = 0, l = thHead.length; i < l; i++) {
$(this).find('td').eq(i + 1).prepend('<h3>' + thHead[i + 1] + '</h3>');
}
});
trAcc.append('<i class="icon-accordion">+</i>');
trAcc.click(function () {
if ($(this).hasClass('accordion-opened')) {
$(this).animate({
maxHeight: '60px'
}, 200).removeClass('accordion-opened').find('.icon-accordion').text('+');
} else {
$(this).animate({
maxHeight: '1000px'
}, 400).addClass('accordion-opened').find('.icon-accordion').text('-');
}
});
});
};
// Init
$(function () {
$('.js-responsive-table').responsiveTable();
});