Load More Content - Remove Load More Button or Change Load More to Load Less

Viewed 45

Have 8 rows showing with a button to load 8 more.

Trying to adjust button so when it reaches the end of showing all expandable divs (8 at a time), "Load More" button would change to "Load Less" and collapse upwards 8 at a time until it reaches its original load of just 8 boxes.

codepen with HTML/CSS/Javascript is here.

If possible, is there a way to adjust the JS so that:

The button adjusts from "load more" to "load less" instead of showing "No Content" which it does now?

The current JS can be found on the Codepen but also here:

$(document).ready(function(){
  $(".content").slice(0, 8).show();
  $("#loadMore").on("click", function(e){
    e.preventDefault();
    $(".content:hidden").slice(0, 8).slideDown();
    if($(".content:hidden").length == 0) {
      $("#loadMore").text("No Content").addClass("noContent");
    }
  });
  
})

Thanks!

1 Answers

I would do something like this. Use a class to determine if showing or hiding and change the classes depending on how many boxes are being shown

$(document).ready(function(){
  $(".content").slice(0, 8).show();
  $("#loadMore").on("click", function(e){
    e.preventDefault();
    if (!$(this).hasClass('less')){
      // More Mode
      $(".content:hidden").slice(0, 8).slideDown('400', function(){
        // this runs after animation is finished..
        if($(".content:hidden").length == 0) {
          // All being shown, switch to Less Mode
          $("#loadMore").text("Load Less").addClass("less");
        };
      });
    }else{
      // Less Mode
      l = $(".content:visible").length;
      $(".content:visible").slice(l-8, l).slideUp('400', function(){
        // this runs after animation is finished..
        if($(".content:visible").length == 8) {
          // Only the original are shown, switch to More Mode
          $("#loadMore").text("Load More").removeClass("less");
        };
      });
    };
  });
});

Note: 400 is the default slide up/down speed

Related