If the number of list items exceeds 3, hide the additional ones and add them to the HTML using jQuery

I have a large list of items and I am interested in displaying only the first 3 items initially.

When a button is clicked, I want to reveal the hidden items. Rather than cutting off words mid-way as it currently does, I prefer to hide entire words that exceed the character limit.

An error message appears stating that jQuery(...).length is not a function.

jQuery(function () {
    var maxLimit = 3;
    var itemList = jQuery('.outer-card-expand li');
    jQuery(itemList).each(function () {
        
        var totalItems = jQuery(itemList).length();
        if(totalItems.length > maxLimit) {
            
            var beginning = totalItems.substr(0, maxLimit),
                ending = totalItems.substr(maxLimit);

            jQuery(this).html(beginning + '<span class="dots">...</span>')
                .append(jQuery('<div class="see-more see-more-closed">').html(''))
                .append(jQuery('<span class="hidden text-thats-hidden">').html(ending))
        }
    });
});
.hidden {
   display: none!important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="outer-card-expand">
   <li></li>
   <li></li>
   <li></li>
   <li></li>
   <li></li>
</div>

Answer №1

One way to achieve this is by implementing the following code:

jQuery(function() {
  var maxLimit = 3;
  // define maximum number of items to display
  var totalItems = jQuery('.outer-card-expand li').length;
  // get current number of items
  if (totalItems > maxLimit) {
    // check if current number exceeds set limit
    jQuery('.outer-card-expand li:nth-child(+n+' + (maxLimit + 1) + ')').addClass("hidden")
    // hide additional items beyond the defined limit
    jQuery('<li><span class="dots">...CLICK</span></li>').insertAfter(jQuery('.outer-card-expand li:last-child'));
    // insert a span with dots or any desired content
  }

});


jQuery(document).on("click", ".dots", function() {
  // when dots are clicked, reveal hidden items and remove the dots parent li element
  jQuery('.outer-card-expand').find(".hidden").removeClass("hidden")
  jQuery('.outer-card-expand').find(".dots").parent("li").remove()
});
.hidden {
  display: none!important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="outer-card-expand">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
  </ul>
</div>

Check out this resource for more information on how CSS selectors work in this example:

Is it possible to select the last n items with nth-child?

Answer №2

Consider adding a hidden class directly to any additional list items beyond the maximum limit,

and insert a div to display others, without needing an extra loop or wrapper.

Utilize the gt expression as follows: li:gt(${maxL-1})

apply the selector based on the condition :

if(listItems.length > maxL) {
   $(`.outer-card-expand li:gt(${maxL-1})`).hide()
}

Take a look at the example snippet below:

$(function () {
    var maxL = 3;
    var listItems = $('.outer-card-expand li');
    
    $(document).on("click",".see-more-closed", function(e){
       $('.outer-card-expand li').show(300);
       $(this).hide();
    })
    
    if(listItems.length > maxL) {
     $(`.outer-card-expand li:gt(${maxL-1})`).hide();
     
     $('.outer-card-expand ul').append('<div class="see-more see-more-closed">')
     
     
    }
    
});
.see-more-closed:after {
  content:"more >";
  cursor:pointer;
  font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="outer-card-expand">
  <ul>
   <li></li>
   <li></li>
   <li></li>
   <li></li>
   <li></li>
   <li></li>
   <li></li>
   <li></li>
   <li></li>
  </ul>
</div>

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

What is the best way to right-align navigation using bootstrap?

We are struggling to align our navigation items to the right side of our page. Despite using a container class and align-items-end, we have not been successful in achieving this. We must confess that this section is somewhat hastily put together, and we do ...

What causes the sudden disappearance of all information when I simply press a button?

I am currently working on a website that allows users to switch between languages, specifically Polish and English. All text on the website changes languages accordingly. However, I have encountered an issue with the menu functionality. The menu consists ...

Is there a way I can put together this CSS code?

I am currently using Socialengine (Zend Framework) along with several plugins. However, one of the plugins has its own unique CSS style. There are multiple CSS cascades in use, but they are not less or sass files. The contents of my file style.css are as ...

Screening out specific BBCodes for designated elements

Describing my desired outcome is simple, but as a PHP novice, achieving it proves to be quite challenging. My goal is to streamline BBCodes, making them more concise and easier to use. Instead of using an array like $filter=array( '[b]'=> ...

break-word property not functioning correctly within pre tag

Each row in my dataTable triggers a modal to appear: <div id="verifyModal" class="modal"> <div class="modal-content"> <h2>Verify # <span id="verify-modal-id"></span></h2> <pre><code class="" id="verif ...

Switch between divs using an update panel

Consider this scenario: Numerous div controls are present on an aspx page, and update panels are being used to prevent page refresh. These divs contain various controls like buttons and textboxes: <asp:UpdatePanel ID="UpdatePanel1" runat="server"> ...

I am encountering an issue with image sliding when trying to implement it within a ViewBag foreach loop in ASP.NET

I'm currently working on a project that involves displaying images in a slideshow with accompanying text. However, I've encountered an issue where all the images are being displayed in a single line, one after another, instead of looping through ...

Using ajax to retrieve data by applying multiple criteria

Currently, I am utilizing AJAX to retrieve database data and compare it with a variable in order to display the information. At the moment, I am only comparing based on one condition in the "Where" clause, specifically whether the field ID is equal to a ...

Styling with CSS to have radio buttons positioned on the left side of the label

Struggling to shift the labels of my radiobuttons to the left using CSS, but nothing seems to be working. Can anyone lend a hand with this? asp:RadioButtonList ID="rbid" runat="server" RepeatDirection="Vertical" RepeatLayout="Table" TextAlign="left" > ...

Easily implement a JavaScript function to enable full-screen YouTube video playback with a single click

Looking for a simple JavaScript function that plays YouTube videos in fullscreen mode upon clicking, without utilizing the YouTube API. The current setup works well but I am aiming to achieve this using pure JavaScript and an onclick event trigger. < ...

When history.go(-1) is employed, the jQuery Multiselect length property reverts to its default value

In my project, I have a multi-select dropdown and an external div that displays the number of selections. However, when I save the document as XML, a window opens with an option to go back using onclick="history.go(-1);"). The issue is that even though the ...

What steps can be taken to modify Gmail settings so that annotations are visible in the promotions tab?

I'm currently looking into how to properly utilize annotations in the promotion tab. I sent a test email to myself, but I am unable to see any annotations in my promotion tab. Is there a specific setting within Gmail that needs to be adjusted in order ...

Interactive html5 canvas game with swiping mechanism

Currently, I am in the research phase for a new HTML5 canvas game that I want to create as a personal project to enhance my skills. Surprisingly, I have not been able to find any valuable articles or tutorials online about creating swipe-based games. The ...

Utilizing jQuery's map function to extract data attributes from lists and store them in an array

View the working example Check out the failed example I'm currently utilizing a pie chart plugin available on GitHub. My objective is to generate an array resembling the structure below: [["Male",12,"some text","#222"], ["Fe ...

What is the best way to create a page that moves on release using HTML/CSS?

I'm working on a website where I want to make an interactive feature. When users click on an image on the left side of the page, I want the page to move backward. Similarly, when they click on an image on the right side, I want the page to move forwar ...

Ways to ensure that I return only after my callback has finished executing

I'm currently working on a Node.js app and I'm encountering an issue with returning the value of my web scrape to the main app.get function. The scraping process is successful, and the results reach the RETURN statement in my callback function. H ...

Ensure that the table is padded while keeping the cells collapsed

I am currently working on creating a table with borders between each row. However, I am facing an issue where the row borders are touching the outer border of the table. Despite my efforts, I have been unable to find a solution to this problem. I feel like ...

Transforming a sophisticated nested array containing named values into JSON format

I am facing a challenge with converting an array into JSON format. The array, named classProfiles, has the following structure (seen after inspecting console output): Buildings_clear: Array(0) band1: [Min: 24, Max: 24, Mean: 24, Median: 24, StdDev: 0] ...

Utilize Mapbox-GL.JS to animate several points along designated routes

I'm encountering issues with the following example: Animate a point along a route My goal is to add another point and routes in the same map container. Here's what I've tried so far: mapboxgl.accessToken = 'pk.eyJ1IjoicGFwYWJ1Y2t ...

How can I prevent Javascript click events from cascading, or ensure proper assignment to multiple divs in my code?

My goal is to create a single-page website where different sections are revealed or hidden based on navigation button clicks. However, I'm encountering issues with certain buttons not working unless the first button is clicked. Additionally, there&apo ...