JavaScript slice() method displaying the wrong number of cards when clicked

In my code, I have a section called .registryShowcase.

This section is designed to display logos and initially shows 8 of them. Upon clicking a button, it should load the next set of 8 logos until there are no more left to load (at which point the button should disappear).

However, I am encountering some issues with my current implementation:

  1. When I click the #registryShowcase-loadmore button, logos start showing up in other .registryShowcase sections on the same page.
  2. The #registryShowcase-loadmore button in the first section does not hide itself even after all logos have been loaded.
  3. Section 2 only loads 6 additional logos instead of the defined next 8 logos.

Demo

$(function() {

  const loadmoreBtn = $('.registryShowcase-loadmore');
  const hiddenCard = $('.registryShowcase__card:hidden');
  var x = 8;

  loadmoreBtn.on('click', function(e) {
    e.preventDefault();
    x = x + 8;
    hiddenCard.slice(0, x).fadeIn().addClass("registryShowcase__card--flex");
    if (hiddenCard.length == 0) {
      loadmoreBtn.fadeOut();
    }
  });

});
:root {
  --navy: #0E185F;
  --white: #FFFFFF;
}

.registryShowcase {
  padding: 139px 0 140px 0;
}

.registryShowcase__card {
  display: none;
}

.registryShowcase__card--flex,
.registryShowcase__card:nth-child(-n+8) {
  display: flex !important;
}

.registryShowcase__box {
  margin-bottom: 21px;
  background-color: var(--white);
  border-radius: 26px;
  padding: 48px 38px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex: 1;
}

.registryShowcase__btn {
  margin-top: 43px;
}

.registryShowcase__btn a {
  color: #FF6575;
}

.registryShowcase__btn a:hover {
  color: var(--white);
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b6964647f787f796a7b4b3e253b2539">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<!------------------------------>
<!-- SECTION 1 (has 10 items) -->
<!------------------------------>

<section class="registryShowcase" style="background-color: #0145A4;">
  <div class="container">
    <div class="row">

      <div class="col-6 col-md-2 col-lg-3 registryShowcase__card">
        <div class="registryShowcase__box text-center">
          <img class="registryShowcase__logo" src="https://7944074.fs1.hubspotusercontent-na1.net/hubfs/7944074/website/images/logos/colored/salesforce-logo.svg" alt="logo">
        </div>
      </div>

      <!-- Additional logo elements omitted for brevity -->

    </div>

    <div class="row" data-animate="fadeInUp">
      <div class="col-12">
        <div class="registryShowcase__btn d-flex justify-content-center">
          <a class="button registryShowcase-loadmore" href>Load more</a>
        </div>
      </div>
    </div>

  </div>
</section>

<!------------------------------>
<!-- SECTION 2 (has 14 items) -->
<!------------------------------>

<!-- Section 2 HTML markup omitted for brevity -->

Answer №1

Modifying the code slightly, imagine a scenario where each section manages its visible card count using a data attribute.

By utilizing [data-cards-to-load] and [data-cards-to-show], you can specify the number of cards to be shown initially and loaded with each button press.

In this updated version, the second section displays 6 cards at the start and loads an additional 8, while the first section presents 6 cards initially and loads another 6 per click of the button.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for choosing a text node that is a child of a span node

I am facing an issue with selecting the Active user with tag number 00015339 on my webpage. I am unable to write a correct xpath for it. What I really need is an xpath that can retrieve all Active users regardless of their tag numbers. Below is the code s ...

What steps can I take to alter this situation?

I am working on creating an API Code. Here is the code I have written: When we run the code, it displays as follows: website <?php include('simple_html_dom.php'); $url = 'https://www.g2g.com/wow-us/gold-2299-19249?&server=30805&a ...

Issue encountered while attempting to save hook arrays: Uncaught TypeError - 'choices' is not able to be

I'm in the process of creating a straightforward multiple-choice exam form that includes choices and answers. Whenever a user selects an option, it should be added to the array of choices. At the start, I have an array called exercises, which consist ...

I am facing issues with utilizing if endif for my Internet Explorer stylesheet in HTML/CSS

<!--[if IE]> <link rel="stylesheet" type="text/css" href="ie.css" /> <![endif]--> <link rel="StyleSheet" href="style.css" /> Whenever I apply this code, the content in Internet Explorer is being influenced by both style.css and ie. ...

The click event for jQuery is failing to trigger on every link

Currently, I'm in the process of creating a "collapse all" button for the Bootstrap 3 collapsible plugin. It appears to be functioning correctly, but only when there is just one collapsible on the page. Once I add another one, the method only works on ...

Preserve line breaks within HTML text

Utilizing the powerful combination of Angular 5 and Firebase, I have successfully implemented a feature to store and retrieve movie review information. However, an interesting issue arises when it comes to line breaks in the reviews. While creating and edi ...

Online application for saving a vast quantity of information on the user's device

Is there a way for a web application to store an extensive amount of data client-side, allowing for millions of records to be accessed offline by users exclusively on Chrome? I initially considered indexedDb, but I discovered it becomes almost unusable wi ...

Guide to extracting additional data from a JSON array upon selection of a value within an option tag using jQuery

Seeking assistance to enhance the display of museum information when a museum name is selected from an option dropdown box. The data is extracted from a json array. Although I managed to populate the option box with the museum names, I am encountering di ...

Page encountering NextJS cors error, while API route remains unaffected

In my Next.js application, I have encountered an issue where executing a call to fetch a page from an external website works perfectly fine when done from the backend through an API route. However, when attempting the same action from the frontend, I encou ...

What is the best way to retrieve the ID of the list item that has been clicked during a button event?

How can I use jQuery to get the ID of a selected list item when clicking a button in my HTML code? <ul id="nav"> <li><a href="#" rel="css/default.css" id="default" > <div class="r1"></div> </a>< ...

jQuery Refuses to Perform Animation

I'm facing an issue with animating a specific element using jQuery while scrolling down the page. My goal is to change the background color of the element from transparent to black, but so far, my attempts have been unsuccessful. Can someone please pr ...

Mastering the art of resolving a dynamic collection of promises with '$.all'

Imagine having 3 promises and passing them to $q.all. This results in a new promise that resolves when the 3 promises are resolved. But what if I realize before the 3 promises resolve that I also want a 4th promise to be resolved? Can this be achieved? I ...

Occurrences repeating several times following the incorporation of fresh content into the DOM

I am facing an issue with my plugin. I have implemented an update method to handle new elements added to the DOM. Initially, everything works perfectly without any errors or issues. However, when a new element (div with class "box") is added to the DOM, th ...

The socket.rooms value is updated before the disconnection listener finishes its process

When dealing with the "disconnect" listener, it's known that access to socket.rooms is restricted. However, I encountered an issue with my "disconnecting" listener. After making some modifications to my database within this callback, I attempted to em ...

How can I prevent an image from scrolling on a webpage?

I am seeking a way to prevent an image from scrolling along with the rest of the page. I want the image to occupy a specific percentage of width, while allowing the browser to determine the appropriate height for display. The image's height should als ...

How to toggle two classes simultaneously using JQuery

Check out this code snippet: http://jsfiddle.net/celiostat/NCPv9/ Utilizing the 2 jQuery plugin allows for the following changes to be made: - The background color of the div can be set to gray. - The text color can be changed to red. The issue arises wh ...

Error Message: Unable to retrieve property "country" as the variable this.props is not defined

Currently, I am developing a react application However, when running this function using infinite scroll, an error is encountered An Unhandled Rejection (TypeError) occurs: Unable to access the "country" property, since this.props is undefined async pa ...

Content overflowing beyond the boundaries of the parent DIV in Internet Explorer 6

Take a look at the code snippet below: <div style="width: 50px; border: 1px solid green;"> <div style="position: absolute;"> add whatever text you'd like </div> </div> The display in modern browsers (such as I ...

javascript if an error occurs, refresh the webpage

Currently, I am inquiring about the most effective method for managing JavaScript errors. Given that my application relies heavily on JavaScript, despite diligent testing efforts, encountering bugs is almost certain. I'm interested in knowing if ther ...

Extract the price value from the span element, then multiply it by a certain number before adding it to a div element

On the checkout page of my website, I have the following HTML: <tr class="order-total"> <th>Total</th> <td><strong><span class="woocommerce-Price-amount amount"> <span class="w ...