pocockn
pocockn

Reputation: 2063

Hiding the last 3 items in a list jQuery

I am creating a basic feature for my site that gets all the related posts and displays them in my sidebar. After this I hide all of them but 3 and then display a 'view more' button, when clicking the view more button It then displays a further 3 related posts. When all the posts have been displayed the button changes to 'view less' and if this button is clicked it should remove the last 3 posts, however at the moment it removes the top 3 posts.

Here is my code:

   <div class="col-md-5">
      <h4>Method</h4>
      <?php echo $rows['steps']; ?>
    </div>
    <div class="col-md-3">
      <h2> Related Recipes </h2>
      <ul class="related-recipes">
      <?php 
      $recipeNumber = 0;
      foreach ($related_recipes as $related_recipe) { ?>
        <li>
          <h4><?php echo $related_recipe['recipe_name']; ?></h4>
          <a href="single-recipe.php?id=<?php echo $related_recipe['recipe_id']; ?>"><img src="<?php echo $related_recipe['recipe_image'];?>" style="width:50%; height:50%;"/></a>
        <?php $recipeNumber++; } ?>
        </li>
      </ul>
      <?php if ( $recipeNumber  > 3 ) { ?>
          <button id="more-recipes" class="view-more" type="button">View More</button>
          <button id="less-recipes" class="view-less" type="button" >View Less</button>
      <?php } ?>
      </div>
  </div>
</div>

    <script>

    $(document).ready(function () {
        $('.related-recipes li:lt(3)').show(); 
        var shown = 3;
        var items = <?php echo $recipeNumber ; ?>;
          $('.view-more').on('click',function() {

            shown = $('.related-recipes li:visible').size()+3;

            $('.related-recipes li:lt('+shown+')').fadeIn(1000);

            if (shown == items) {

                $('#less-recipes').show();

                $( "#more-recipes").hide();

            }

          });

          $('.view-less').on('click',function() {

            shown = $('.related-recipes li:visible').size()-3;

            $('.related-recipes li:lt('+shown+')').fadeOut(1000);

            if (shown < items) {

                $('#less-recipes').hide();

                $( "#more-recipes").show();

            }

          });            
    });

 <style>
      .related-recipes li {
          display:none;
      }

      #less-recipes {
        display:none;
      }

</style>

Upvotes: 1

Views: 731

Answers (1)

klauskpm
klauskpm

Reputation: 3125

You are using

$('.related-recipes li:lt('+shown+')').fadeOut(1000);

jQuery definition :lt definition:

Description: Select all elements at an index less than index within the matched set.

:lt stands for less than, it will select all indexes lower than shown.

The indexes goes from 0 to N, only getting higger.

Try to use :gt instead, and see if it works.

Upvotes: 2

Related Questions