Thursday, 8 August 2013

Animate table with jquery (if possible)

Animate table with jquery (if possible)

I have code that shows dynamically created tables of varying lengths, with
'expand' and 'condense' buttons that show/hide extra table rows. It works
but it's ugly. I'd love to animate it but apparently that's not possible.
This is probably a duplicate of jQuery - How to Use slideDown (or show)
function on a table row?, in which case feel free to close it, but that
was four years old and I was hoping there might be a new/better solution
(I couldn't get those to work, but I can keep trying). If animating is not
an option, maybe someone can suggest some other design feature that might
look decent?
$(document).ready(function(){
$('.table').each(function(){
$(this).find("tr:even").addClass("even");
$(this).find("tr:odd").addClass("odd");
var numShown = 2; // Initial rows shown & index
var $table = $(this).find('tbody'); // tbody containing all the rows
var numRows = $table.find('tr').length; // Total # rows
var tableWidth = $table.find('tr:first td').length;
var expandDiv = '<tbody class="more"><tr><td colspan="' +
tableWidth + '"><div>Show
More</div</tbody></td></tr>';
var condenseDiv = '<tbody class="less"><tr><td colspan="' +
$table.find('tr:first td').length + '"><div>Show
Less</div</tbody></td></tr>';
if(numRows>numShown){
$(function () {
// Hide rows and add clickable div
$table.find('tr:gt(' + (numShown - 1) + ')').hide().end()
.after(expandDiv);
})
};
$(this).on('click', '.more', (function() {
// numShown = numShown + numMore;
$(this).remove();
$table.find('tr').show();
$table.after(condenseDiv);
}));
$(this).on('click', '.less', (function() {
$table.find('tr:gt(' + (numShown - 1) + ')').hide().end()
.after(expandDiv);
$(this).remove();
})
)
});
});

No comments:

Post a Comment