Dan Dan - 5 months ago 42
jQuery Question

Show more on click on table

I have got to a stick point with my JQuery where I need some assistance, I am trying to create a show more on table rows but I want to show initially the first 10 and then load them by 10 at a time but at the moment its 1 and 1 at a time:

<script type="text/javascript">
var curr = 0;
var rowN = $('.table tr').length;

$('.table tr').eq(curr).siblings().hide(); // hide all but current one

e.preventDefault(); // prevent default anchor behavior
$('.table tr').eq(++curr).show();


I have tried to alter the current but it just starts at a certain row number and not row 1 so I want it to show the first ten and then on click loads the next ten and so on...


A better solution which avoids the use of a global variable is to put a class on the shown rows. You can then use that class to find the index of the last visible element and show the next group of elements. Try this:

$('table tr:first').addClass('active');

$('a.load_more').on('click', function(e) {
  var $rows = $('table tr');
  var lastActiveIndex = $rows.filter('.active:last').index();
  $rows.filter(':lt(' + (lastActiveIndex + 3) + ')').addClass('active');
table tr { display: none; }
table tr.active { display: table-row; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <tr><td>Row 1</td></tr>
  <tr><td>Row 2</td></tr>
  <tr><td>Row 3</td></tr>
  <tr><td>Row 4</td></tr>
  <tr><td>Row 5</td></tr>
  <tr><td>Row 6</td></tr>
  <tr><td>Row 7</td></tr>
  <tr><td>Row 8</td></tr>
  <tr><td>Row 9</td></tr>
  <tr><td>Row 10</td></tr>

<a href="#" class="load_more">Load more</a>

In the above sample it displays 2 further rows per click, but this can easily be amended as required.