Hashaam
Hashaam

Reputation: 125

How do I show next x limit li when click on show more button using jquery

I have following script ,work perfectly . it only show first x element li and after click on show more it show all . how can i make limit when click on show more button , like i need x element show , next x element show and soo on here is my code

$('.tabNav ul').each(function() {
  var LiN = $(this).find('li').length;
  if (LiN > 3) {
    $('li', this).eq(5).nextAll().hide().addClass('toggleable');
    $(this).append('<li class="more">More...</li>');
  }
});

$('.tabNav ul').on('click', '.more', function() {
  if ($(this).hasClass('less')) {
    $(this).text('More...').removeClass('less');
  } else {
    $(this).text('Less...').addClass('less');
  }
  $(this).siblings('li.toggleable').slideToggle();
});

Your help would be greatly appreciated.

Upvotes: 1

Views: 2111

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67515

Here is an idea of how you could toggle using step with the use of slice.

var step_nbr = 2;
var min_nbr = 6;

$('.tabNav ul').each(function() {
  var LiN = $(this).find('li').length;
  if (LiN > 3) {
    $('li', this).eq(5).nextAll().hide().addClass('toggleable');
    $(this).append('<li class="more">More...</li>');
  }
});

$('.tabNav ul').on('click', '.more', function() {
  var visible_lis = $('.tabNav ul li:visible').length;

  if ($(this).hasClass('less')) {

    $(this).prevAll('li:not(.toggleable)').slice(0, step_nbr).addClass('toggleable').hide();

    if ($('li:visible').length <= (min_nbr + 1)) {
      $(this).text('More...').removeClass('less');
    }

  } else {
    $(this).siblings('li.toggleable').slice(0, step_nbr).removeClass('toggleable').show();

    if ($('li.toggleable').length == 0) {
      $(this).text('Less...').addClass('less');
    }
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tabNav">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
    <li>10</li>
  </ul>
</div>

Upvotes: 1

Related Questions