What is the best way to display just the first four HTML elements while concealing the others?

Looking for a solution to display only the first 4 child elements of a menu list initially, with the option for users to click 'show more' to reveal the remaining items? Want to achieve this using CSS, JavaScript, and jQuery without altering the HTML structure. Here's an example of the menu setup:

https://i.sstatic.net/P7S8r.png

In this layout, the bold text represents the parent elements, while the thin text corresponds to the child elements. The goal is to hide the extra child items and provide a toggle feature for showing or hiding them on user interaction.

This can be achieved by efficiently managing the visibility of the child elements through scripting. Here's how the child elements are structured in the HTML:

<div>
  <div class="nav-item level2"><a href="#" class=" nav-anchor"><span>Body Oil</span></a></div>
  <div class="nav-item level2"><a href="#" class=" nav-anchor"><span>Foot Care</span></a></div>
  <div class="nav-item level2"><a href="#" class=" nav-anchor"><span>Lip Service </span></a></div>
  <div class="nav-item level2"><a href="#" class=" nav-anchor"><span>Massage</span></a></div>
  <div class="nav-item level2"><a href="#" class=" nav-anchor"><span>Sunscreen</span></a></div>
  <div class="nav-item level2"><a href="#" class=" nav-anchor"><span>Eye Cream</span></a></div>
</div>

Answer №1

Utilize the nth-of-type selector as shown below. To toggle between showing more and less content, use the toggleClass method.

$('#more').on("click", function() {
  var text = $(this).text();
  if (text == 'Show-More') {
    $(this).text('Show-Less');
    $('.nav-item').toggleClass("nav-item newClass");
  } else {
    $('.newClass').toggleClass("newClass nav-item");
    $(this).text('Show-More');
  }
});
.nav-item:nth-of-type(1n+5) {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div>
  <div class="nav-item level2"><a href="#" class=" nav-anchor"><span>Body Oil</span></a></div>
  <div class="nav-item level2"><a href="#" class=" nav-anchor"><span>Foot Care</span></a></div>
  <div class="nav-item level2"><a href="#" class=" nav-anchor"><span>Lip Service </span></a></div>
  <div class="nav-item level2"><a href="#" class=" nav-anchor"><span>Massage</span></a></div>
  <div class="nav-item level2"><a href="#" class=" nav-anchor"><span>Sunscreen</span></a></div>
  <div class="nav-item level2"><a href="#" class=" nav-anchor"><span>Eye Cream</span></a></div>
  <span id='more'>Show-More</span>
</div>

Answer №2

The simplest method is:

  1. Include Show More and Show less li.
  2. Attach the event handlers to these lis.
  3. Display/Hide appropriate li based on the list size.

Below is the implemented code:

$('.show-more').on('click', function() {
  $('.nav-menu li:gt(3)').show();
  $('.show-less').removeClass('hidden');
  $('.show-more').addClass('hidden');
});

$('.show-less').on('click', function() {
  $('.nav-menu li:gt(3)').hide();
  $('.show-more').removeClass('hidden');
  $('.show-less').addClass('hidden');
});

//Show only four items
if ($('.nav-menu li').length > 4) {
  /*$('.nav-menu li:gt(3)').hide();
  $('.show-more').removeClass('hidden');
  */

  $('.show-less').click();
}
.show-more,
.show-less {
  font-size: 13px;
  line-height: 140%;
  background-color: rgba(120, 120, 200, 0.5);
  display: inline-block;
  cursor: pointer;
}

.hidden {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="nav-menu">
  <li class="nav-menu-item level2"><a href="#" class=" nav-anchor"><span>Body Oil</span></a></li>
  <li class="nav-menu-item level2"><a href="#" class=" nav-anchor"><span>Foot Care</span></a></li>
  <li class="nav-menu-item level2"><a href="#" class=" nav-anchor"><span>Lip Service </span></a></li>
  <li class="nav-menu-item level2"><a href="#" class=" nav-anchor"><span>Massage</span></a></li>
  <li class="nav-menu-item level2"><a href="#" class=" nav-anchor"><span>Sunscreen</span></a></li>
  <li class="nav-menu-item level2"><a href="#" class=" nav-anchor"><span>Eye Cream</span></a></li>
</ul>

<div class='show-more hidden'>SHOW MORE>></div>
<div class='show-less hidden'>
  << SHOW LESS</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

Bizarre error when injecting Factory into Controller in AngularJS

After scouring through countless posts on various forums, I have yet to find a solution to my unique problem. I find myself in a peculiar situation where I am trying to inject a Factory into a Controller, and despite everything appearing to be in order, i ...

How to Add Motion to Several Markers

Exploring the concept of moving markers on a map with drawn polylines to simulate simultaneous movement is a fascinating challenge. However, encountering some difficulties, such as only the last marker moving while the others remain stationary, can be frus ...

Remove any elements using jQuery that do not contain any content

I need to remove any empty elements from my HTML code. Here is an example of the HTML markup: The HTML markup is stored in a jQuery variable called 'myhtml' and it may contain various tags. <h1> <u> <strong></st ...

Utilizing an array to pass a series of items to a function parameter

I am currently working on an Angular project that involves a controller and service. In this setup, the controller sends data and an endpoint to the service. As of now, the service handles the http request. However, I am in the process of refactoring my ...

Lost in a sea of confusion with ember-cli-postcss and autoprefixer

I'm currently working on an ember build that incorporates autoprefixer. My issue arises from the fact that the output location for 'assets/application-name.css' has shifted from its normal path to 'app/styles/app.css', and I would ...

Issue with Bootstrap dropdown functionality when used within a Horizontal description block

I'm struggling to get a dropdown menu to work properly within a horizontal description. The dropdown menu just won't toggle when clicked. <div class="container-fluid"> <div class="row vertical-align"> <dl class="dl-horizonta ...

Using JavaScript or jQuery to modify the URL of a webpage

Here is the HTML code I am working with: <form id="search-new"> <input type="text" name="search" placeholder="Search on the Site" value=""> <input id="search-submit" type="button" value="&rsaquo;"> </fo ...

Placing circular buttons below the navigation bar

I'm currently working on implementing a navigation bar on my master page. Here is the code snippet for the navigation bar: <nav class="navbar" style="background-color: #264653; position:absolute; top:0px; left:50%; transform:tran ...

The datetime picker does not have a default value specified

I've been attempting to configure a default value in my bootstrap datetimepicker, but it doesn't seem to be working as intended. var fromDate = "2022-08-24T11:24:00"; $('#inputFromDate').datetimepicker({ format: 'DD/M ...

How important is a neglected parameter in the world of JavaScript?

Curious about the value of an ignored parameter in JS? Imagine a function that requires 2 values as parameters, but you only provide one during the call. What happens to the other parameter? You might think it's undefined, but the code below only show ...

Spontaneous visual paired with text upon refreshing

I am new to Java script and I am working on creating a web page that displays two random numbers every time it is refreshed. Depending on these numbers, specific text should be shown. These numbers are represented by images ranging from 0 to 5. Currently ...

Unravel a Base64 encoded string with the power of CryptoJS

I am in the process of developing a basic webpage where the objective is to send an encrypted message to the server, which will then create a file with that content. Subsequently, a link is generated for the recipient to access the encrypted value by provi ...

Using CSS to ensure that the cards have consistent heights when using both React and Bootstrap

I am currently working with Bootstrap 4 in React. I have encountered an issue where the card for Item 1 is shorter than that of Item 2, and I would like both cards to have the same height. Additionally, I anticipate adding more cards at the bottom in the ...

Creating a customized date picker design with Material UI

Instead of displaying the date in DD/MM/YYYY format, I would like to show "Today" text. For example, when using a datepicker, the browser may display a date like 20/1/2009. However, I want it to show "Today" instead of that specific date. ...

What steps should I take to address this 'key' alert?

My browser console is displaying the following error message: Warning: Each child in a list should have a unique "key" prop. See https://reactjs.org/link/warning-keys for more information. ExpenseList@http://localhost:3000/main.cfec1fef7369377b9a ...

What is the best method for changing a prop in a different component?

I have a list of accounts in my page.js file and I need to access this list in another component that is also rendered within the page.js file: var accounts = []; ... <div className="main"> <LeftPanel accounts={accounts}/> </di ...

What are some ways to stop the form from refreshing while still successfully submitting the form data on the current

As my form continued to submit and refresh, I consulted a helpful resource on Stack Overflow titled How to prevent page from reloading after form submit - JQuery in search of a solution. Interestingly, the difference between the provided answer and my situ ...

The JQuery code restricts the use of multiple buttons within a single instance

UPDATE I am facing an issue where I am trying to add the same set of buttons inside multiple divs, however, it seems that the button set only appears in one div at a time. I want the button set to show up in every location where I place it. Here is the co ...

Modifying the ptTimeSelect functionality in conjunction with the validationEngine plugin

Currently, I am facing a challenge with my input field that is programmed to display the ptTimeSelect time picker while also requiring the use of validationEngine for field required validation. The issue at hand is as follows: When the input field is in ...

Contrasting import and require methods

// script.js file; let x = 0; let updateValue = () => { x = 1; }; export { x, updateValue }; // script1.js import { x, updateValue } from './script.js'; updateValue(); console.log(x); // --> x = 1; however // script.js let x = 0; let ...