I have a table for which I want to display only the first row by default, but display additional X number of rows if a user clicks a "show more" link (and inversely hide the X rows if the user then clicks "show less").
To exemplify, I want the default view when the page loads to be like so:
Top Scores
====================================
| 1 | show this row always! |
====================================
-show more-
Then, if a user clicks "show more", the table should expand with additional rows and look like this:
Top Scores
====================================
| 1 | show this row always! |
| 2 | newly displayed row |
| 3 | newly displayed row |
| 4 | newly displayed row |
| 5 | newly displayed row |
====================================
-show less-
Then obviously if a user clicks "show less" the table returns to default (showing only the first row again).
I'm familiar with the .toggle()
function in jQuery, but not sure if it can be applied here or if I have to do more manual work.
Thanks!
No additional classes, no headers required - http://jsfiddle.net/wgSZs/
$('table').find('tr:gt(0)').hide();
$("button").on("click", function() {
$('table').find('tr:gt(0)').toggle();
});
UPDATE
It might be better to hide the additional rows via CSS instead of jQuery to avoid element shifting while the JS is being downloaded and applied. But still no need to add classes - it's a good idea to keep your markup as clean as possible. You can do this:
table tr { display: none }
table tr:first-child { display: block }
Here is the working example - http://jsfiddle.net/wgSZs/1/
if you mark the added rows with a class like .collapsible
, then you can easily toggle their visibility in javascript.
$('.collapsible').show()
or $('.collapsible').hide()
or $('.collapsible').toggle()
http://jsfiddle.net/iambriansreed/uwfk8/
var initial_rows_to_show = 2;
(function(_rows){
_rows.hide();
$('a.more').toggle(function(){
_rows.show(); $(this).text('less');
},function(){
_rows.hide(); $(this).text('more');
});
})($('tr:gt(' + (initial_rows_to_show - 1) + ')'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With