Hide or show list items in an unordered list using jQuery

I am interested in creating a script that can toggle between "show more" and "show less" functionality for elements in a list. I came across this script:

HTML

<ul id="myList">
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
    <li>Six</li>
    <li>Seven</li>
    <li>Eight</li>
    <li>Nine</li>
    <li>Ten</li>
    <li>Eleven</li>
    <li>Twelve</li>
</ul>
<div id="loadMore">Load more</div>
<div id="showLess">Show less</div>

CSS

#myList li{ display:none;
}
#loadMore {
    color:green;
    cursor:pointer;
}
#loadMore:hover {
    color:black;
}
#showLess {
    color:red;
    cursor:pointer;
}
#showLess:hover {
    color:black;
}

JQUERY

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
        if(x<=3){$('#showLess').hide();}
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
    });
});

https://jsfiddle.net/6FzSb/1550/

Now, I am curious about the functioning of javascript lines 6 and 10, as well as how to hide the "show more" button when all entries are displayed, and how to hide the "show less" button when only 3 entries are left to show.

Answer №1

Follow this approach to achieve the desired outcome

let count = 3;
$("#myList li:lt(" + count + ")").show();
$("#loadMore").click(function() {
    $("#showLess").show();
    count = $("#myList li:visible").length + 3;
    $("#myList li:lt(" + count + ")").show();
    if (count == $("#myList li").length)
        $(this).hide();
});
$("#showLess").click(function() {
    $("#loadMore").show();
    count = $("#myList li:visible").length - 3;
    $("#myList li:gt(" + (count - 1) + ")").hide();
    if (3 == $("#myList li:visible").length)
        $(this).hide();

});

Fiddle

Answer №2

If you're curious about

$('#myList li:lt('+x+')').show();

try searching for 'jquery selector lt' on the web.

Regarding how to toggle show/hide links for more/less content: all the clues are in your code -- you already understand how to calculate the list size (..size()), how to hide and show HTML elements (..hide() and ..show()), so simply implement a couple of if blocks that hide the 'show less' link initially and hide the 'show more' link when clicked.

Answer №3

Take a look at this revised code snippet:

$(document).ready(function () {
size_li = $("#myList li").size();
x=3;
$('#myList li:lt('+x+')').show();
 $('#showLess').hide();
$('#loadMore').click(function () {
    x= (x+5 <= size_li) ? x+5 : size_li;
    $('#myList li:lt('+x+')').show();

    if(size_li == x){
        $(this).hide();
    }else{
        $('#showLess').show();
    }
});
$('#showLess').click(function () {
    x=(x-5<0) ? 3 : x-5;
    $('#myList li').not(':lt('+x+')').hide();        
    if(x <= 3){
        $('#showLess').hide();
    }else{
       $('#loadMore').show(); 
    }
});

});

JSFIDDLE

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

The color scheme detection feature for matching media is malfunctioning on Safari

As I strive to incorporate a Dark Mode feature based on the user's system preferences, I utilize the @media query prefers-color-scheme: dark. While this approach is effective, I also find it necessary to conduct additional checks using JavaScript. de ...

jQuery modal popup failing to display the value of an element

When attempting to display content in a Bootstrap 4.0 modal on an ASP.NET Core 3.1 Razor page, the jQuery shown.bs.modal event seems to be failing to show the element value within the modal. Strangely, logging the assigned value to the console displays it ...

Executing program through Socket.io alert

My NodeJS server sends notifications to clients when certain actions are performed, such as deleting a row from a grid. Socket.io broadcasts this information to all connected clients. In the example of deleting a row, one approach could be adding an `acti ...

How can you switch the property of an object in VueJS?

I am currently working with an array called cars, which contains names of cars as well as a property called starred. My goal is to toggle the value of starred between true and false for each car, ensuring that only one car can have starred set to true at a ...

What is the process for "unleashing" the X Axis following the execution of chart.zoom()?

After setting the scroll strategy to setScrollStrategy(AxisScrollStrategies.progressive), I noticed that my chart was scrolling too quickly due to the fast incoming data. To address this, I decided to set a specific initial zoom level for the chart using c ...

Enhancing Contact Form 7 with features like a 'select all checkbox' and a 'show more/show less button'

I need to include four checkboxes on every contact form 7 throughout the website. The first checkbox should act as a master selector for the other 3 checkboxes. The second checkbox relates to our privacy policy. Checkbox number three is for marketi ...

Personalized jQuery Slider with automatic sliding

I am currently working on creating my own image slider without relying on plugins. 1st inquiry : How can I achieve horizontal animation for the slider? 2nd inquiry : I want the images to cover both the height and width of their container while maintainin ...

Drupal's Colorbox Gallery Formatter

Is there a way to make Gallery Formatter trigger a Colorbox modal when a slide is clicked? I have both modules set up, along with CCK, etc... Additionally, I have confirmed that the colorbox library is properly installed. It seems like it should be a sim ...

What is the best way to eliminate the [lang tag] from a URL in Next.js?

I am looking to eliminate either the /en or the /it from the URL without explicitly adding it. i18next seems to be doing it automatically, and I am unsure how to disable this behavior. I simply want it to happen in the background. https://i.stack.imgur.co ...

The JObject parser abruptly halts its execution without producing any results or indicating any errors

I have been attempting to retrieve and parse a JSON response from a webapi using the following code: var pemail = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="44302b2a3d37042329252d286a272b29">[email protected]</ ...

Mobile display issue with CSS columns when using the :checked pseudo class

I have embarked on the creation of a portfolio website that relies solely on CSS3 to present a grid and filter out thumbnail images. If you're curious about what I've accomplished so far, feel free to take a look here. To achieve the filtering ...

Fixing 500 (Internal Server Error) in Vue.js and Laravel: The Ultimate Guide

Working on a university project using Vue.js and Laravel, I need assistance with sending information to the API. I'm trying to use axios for the POST request, but it's giving me an error: 500 (Internal Server Error). I can't seem to identif ...

As soon as I closed the modal, I noticed that the checked inputs reverted back to

I am using checkboxes within a modal to narrow down my search results. However, I have encountered an issue where when I check multiple checkboxes and then close the modal, the checked inputs become unchecked. Every time I open the modal, I want the check ...

Retrieve information from child components and populate form fields

Currently, I am working on creating a dynamic form that utilizes a sub component to display input fields because creating them statically would exceed a limit. I pass the states for the form I created along with some data and the change form function. Howe ...

I am unable to send back my JSON object

I seem to be having trouble returning a JSON object as all I get is an undefined variable. The code below is supposed to fetch a JSON element from an API. It appears to work within the success: function, but when attempting to use that data elsewhere, it ...

Utilizing Nuxt3's auto-import feature alongside Eslint

I'm having trouble finding an eslint setup that is compatible with Nuxt3's auto-import feature to prevent no-undef errors. I have tried various packages like @antfu/eslint-config, plugin:nuxt/recommended, @nuxt/eslint-config, @nuxtjs/eslint-confi ...

Troubleshooting the lack of updates in a partial view with MS AJAX in ASP.NET MVC

I've implemented a search text box and a button that is meant to display the search results in a partial view using ajax when the button is clicked. Even though I can see data when setting a breakpoint in the partial view, nothing appears on the form. ...

What is the best way to position the logo in the center of the navigation bar, considering there are an unequal number of menu items on each side

As I work on coding a design I found for practice, I am facing the challenge of getting the logo to be centered in the navbar, similar to the layout in the Dribble link below. View Design on Dribble The navigation bar has 4 items aligned on the left and ...

What is the best method to ensure that an image remains at the bottom of a div even as the div's height adjusts?

In my current project, I am facing a challenge with positioning an image in the bottom-right corner of a dynamically changing div. Initially, this is easily achieved by using CSS selectors: #div1 { position: relative; } #div1 img { position: abso ...

How can I align the content within two div elements?

I'm facing a bit of a challenge that I can't seem to figure out. Within a div, I have one photo and inside another div, there is also a photo. I was able to resize both images from the parent and child divs successfully. <div style="width:100 ...