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

An issue occurred with a malformed JSON string when attempting to pass JSON data from AngularJS

I am facing an issue with passing a JSON string in an ajax request. Here is the code snippet: NewOrder = JSON.stringify (NewOrder); alert (NewOrder); var req = { url: '/cgi-bin/PlaceOrder.pl', method: 'POST&apo ...

Execute Javascript to simultaneously open various links in a single action (not using popups)

I am looking to open multiple URLs with a single click event that also redirects to a specified URL. I have attempted this, but it doesn't seem to be working as intended. Here is the HTML code: <a id="mybutton" href="http://example.net/quote" onc ...

Unique browsing key

Is there a specific identifier that can uniquely represent the browser you are currently using? I have two applications logged in through ApiGateWay, and I need to determine whether they are both running on the same browser. Therefore, I require a unique ...

Passing data to server-side PHP script using AJAX technology

Currently, I'm facing an issue with passing variables to a PHP script using onclick. It seems that I am making a mistake somewhere. To demonstrate the problem, let's say I have the following code snippet in my main page: <img src="myImage.jp ...

What is the best method for displaying plain text using the br tag?

My component looks like this: class News extends Component { state = { isSimple: this.props.isSimple } render() { return ( <div> <div className="extended">extended</div> simple text </div&g ...

Looking to restrict the data retrieved from an API while utilizing ReactJS

I am currently fetching transaction data from an API. One of the fields in the response is buyer, which may sometimes be null. As a result, I am excluding any entries with a null buyer. This leads to varying numbers of results being displayed. My goal is t ...

Determine the size of a file in either megabytes or kiloby

I need to determine the size of a file in either megabytes if the value is greater than 1024 or kilobytes if less than 1024. $(document).ready(function() { $('input[type="file"]').change(function(event) { var _size = this.files[0].si ...

The Javascript function must be executed with each page reload

Currently, I am analyzing an asp.net 2 web application that is in my care (even though I did not create it). There seems to be an issue with certain functionalities not working consistently when the page loads, particularly if using Firefox 3 within a vir ...

Should elements be concealed with CSS if they cannot be eliminated with php?

There are times when I struggle to deactivate a function or elements in PHP, particularly in PHP frameworks and CMSs. As a workaround, I often utilize display: none. However, I am concerned about potential issues this may cause in the future. Should I co ...

What is the CSS method for styling a color label on an active input box?

I am trying to achieve a specific effect where the label changes color when the input box is in focus. However, my current CSS code does not seem to be working as expected. Can someone please explain why and provide a solution to fix this issue? .test-l ...

Having difficulty implementing dynamic contentEditable for inline editing in Angular 2+

Here I am facing an issue. Below is my JSON data: data = [{ 'id':1,'name': 'mr.x', },{ 'id':2,'name': 'mr.y', },{ 'id':3,'name': 'mr.z', },{ & ...

External CSS file for Demandware platform

My boss was supposed to train me this year on demandaware knowledge, but ended up quitting, leaving me in the dark. I am scheduled to attend workshops later this year, but for now I am relying on Google and stackoverflow for guidance. Currently, I am wor ...

Guide to accessing HTML elements and saving them in a JSON formatted text using JavaScript

If you have an html form with labels, select boxes, and radio buttons, you can use javascript to store the child elements of that form in a json string format. Here is an example: { "label": { "content": "This is a label" }, "textbox" ...

How to style focused input using Vue2

I have a form that contains multiple input fields, and I want to dynamically add a class to the label tag of the focused input and remove it when another input is selected. Initially, I tried the following code: onInputSelected: function(e) { var la ...

What is the best way to enclose text within a border on a button?

I am trying to create a button with a colored border around its text. Here is the code for my button: <input id="btnexit" class="exitbutton" type="button" value="Exit" name="btnExit"></input> Although I have already added CSS styles for the ...

What is the process for generating SDF-Icons (Mapbox's specialized icons) from PNG files?

I am currently working on changing the icon color of an icon image in Mapbox. According to Mapbox documentation, the only way to do this is by using sdf-icons (https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#paint-symbol-icon-color). After hours o ...

Comparing JS Async/Await, Promise, and Callbacks: Which is Best

I'm trying to wrap my head around the differences between callbacks, promises, and async/await. While I understand how callbacks and promises work, I'm struggling with grasping the usage of async/await. I know it's essentially a syntactic su ...

Creating an Interactive and Engaging 3D Experience on Facebook with the Power of Javascript API

Looking for suggestions on a 3D API in JavaScript that can be used to create immersive applications on Facebook. Is there something similar to this one: ? Appreciate any insights. ...

What is the best method to remove the x and up/down arrow components of an input date field?

My main objective is to have the orange triangle display in the box, but I'm unsure if CSS or another method is needed to remove the two elements on the left side of the triangle. Is there a way to achieve this? Currently, I am using the input type d ...

Arranging arrows strategically along a line and ensuring they are positioned correctly above all div elements

I'm really struggling with this issue. I have a situation where I need to center a downward pointing arrow within some divs. It should be positioned in the middle, on a brown line, and on top of everything else. The last div should also include the a ...