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

Executing javascript code within the success function of the $ajax method in jQuery: A step-by-step guide

The code snippet below includes a comment before the actual code that is not running as expected. $(document).on('click', '#disable_url', function (e) { e.preventDefault(); var items = new Array(); $("input:checked:no ...

Issue with AngularJS ngGrid rendering incorrect page size and malfunctioning pagination

I'm currently working on implementing ngGrid data pagination for some data retrieved from a service. The table displays correctly and the search filter is functional. However, despite setting the pageSize in my pagingOptions to 25, the table shows all ...

struggling to access the value of a hidden field by using the parent class name

My coding experience so far looks like this- <tr class="chosen"> <td id="uniqueID">ABCDE5678</td> <input type="hidden" value="000005678" id="taxCode"> <td id="fullName">Z, Y</td> </tr> In this scenario, I need to ...

How to efficiently transfer data between Node and Angular 7 using Electron

After setting up an Angular 7 application running on http://localhost:4200, I developed a Node JS application responsible for authenticating users on Facebook, accessible at http://localhost:3000. The callback redirection functions correctly within the No ...

Retrieve all items from the firebase database

I have a query. Can we fetch all items from a particular node using a Firebase cloud function with an HTTP Trigger? Essentially, calling this function would retrieve all objects, similar to a "GET All" operation. My next question is: I am aware of the onW ...

Using CSS Classes with PHP Variables in Conditionals: A Handy Guide

I have limited experience in programming and I'm attempting to edit a .php file within a Wordpress theme. Please keep this in mind as I explain my issue. Within the theme, there is code that calculates the average score from 1 to 10 and then displays ...

I am interested in learning how to utilize jQuery to decode JSON Unicode within a Select2 dropdown filtering system

I am currently utilizing Select2 JS and Datatables JS to handle data in JSON format. However, I encountered an issue where the value Animal & Veterinary is displayed differently in JSON as Animal \u0026amp; Veterinary, and on the Select2 filter as ...

Unable to load when clicking

I am having trouble getting the following script to execute properly. Any advice or suggestions would be greatly appreciated. I am attempting to retrieve external content from other pages. When I manually input the code, it functions correctly. However, ...

Issue with passing props to screen not displaying on initial load

Greetings, I'm a newcomer to the world of react native and currently facing an issue: const Tab = createMaterialTopTabNavigator(); export const CurriculumMenu = ({navigation, item}) => { const data = item.Title; console.log(data) return ( ...

Sending documents to a printer directly from a Rails application

Is there a library or gem in Rails that can be used to print the contents of a web page directly onto paper? I am curious if it's possible to specify only a specific part of the page, such as a div, for printing. Any guidance, advice, or tutorial link ...

Is there a way to customize the slicing of *ngFor in a component according to the components it is being injected into?

This code snippet represents a component that needs to be included in other components: <div class="row"> <div class="col-12 [...]" *ngFor="let course of courses"> <div class="card"> ...

Exploring JqueryUI tab navigation with the help of the <a> tag

I have come across several articles mentioning the possibility of navigating JqueryUI tabs using a button or anchor tag. Here is the method I am currently using: $("#vtabs").tabs(); $("#tabsinner").tabs(); $(".changeTab").click(function() { alert("as ...

Sending SQL queries with multiple selections, each containing three values for every option

I am faced with a challenging question that will require me to dedicate long hours towards solving it and finding a solution. Imagine I have a multiple select element with various options, each consisting of 3 values: One value for the language name One ...

Retrieve data that resets to undefined upon reloading from an array

Encountering an unusual error while working with TypeScript for the first time. Initially, when I use console.log(data), it displays an array with objects. However, upon reloading the webpage without making any changes, the console log shows undefined. con ...

fixing errors with express, angularJS, and socket.io

I am currently in the process of setting up Socket.io on my website using ExpressJS and AngularJS NodeJS server.js var express = require('express'); var app = express(); fs = require('fs'); // specifying the port ...

Radiobutton becomes unchecked when a clone is removed from the DOM

When I make an Ajax call in a bootstrap modal and replace the contents (.modal-contents) with a partial view upon success, an interesting issue arises. There is a radiobutton in the partial view that is initially checked by default. However, after callin ...

Creating image links in this jQuery Slider plugin: A beginner's guide

Currently, I am attempting to insert links into each photo within the slider. While I have successfully done this on two other websites, I am encountering difficulties due to variations in the code structure. <a href="http://www.google.com I have expe ...

React text hover image functionality

Just diving into the world of React and attempting to create a cool image popup effect when you hover over text in my project. I could really use some guidance on how to make it function within React, as the logic seems a bit different from plain HTML. Any ...

Angular is unable to bind with 'dragula' because it does not recognize it as a valid property of 'ul'

I've been attempting to incorporate dragula into my Angular 2 application, but I'm struggling to get it functioning. This is what I have added in my app.module.ts file: import { DragulaModule, DragulaService } from 'ng2-dragula/ng2-dragula ...

When floated to the right, the element is being pushed onto the next line in Firefox

Within a div, there are four elements. I specifically want the last element to be positioned on the far right, so I applied float: right to it. However, in Firefox, the last element gets pushed to the end of the next line instead. This issue does not occ ...