Only allow scrolling if the number of child elements exceeds a certain limit

I am looking to implement a scroll feature on the <ul> element when the number of <li>s exceeds a certain threshold. For example, if we have 12 children, I want to display only 7 of them and then scroll through the rest.

This is my current approach:

$(document).ready(function(){
  $("ul.ul-scrollable, ol.ul-scrollable").each(function (key, val) {
    max_num = $(this).attr('data-maxVisible') || 8;
    //console.log(max_num);
    var lis = $(this).children('li');
    if(lis.length > max_num) {
      maxHeight = 0;
for(i = 0; i < max_num; i++) {
      maxHeight += +$(lis[i]).outerHeight(true);
      //console.log(maxHeight);
      }
      $(this).css({'max-height' : maxHeight + 'px', 'overflow-y' : 'auto'});
    }
  });
});
ul {
  background: white;
  width: 70px;
}
ul li {
  padding: 3px;
  margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul class="ul-scrollable" data-maxVisible="7">
<li>li1</li>
<li>li2</li>
<li>li3</li>
<li>li4</li>
<li>li5</li>
<li>li6 li6 li6</li>
<li>li7</li>
<li>li8</li>
<li>li9</li>
<li>li10</li>
<li>li11</li>
<li>li12</li>
<li>li13</li>
</ul>

However, the height calculation is not working as expected.

JS FIDDLE

Answer №1

A simpler method to achieve the same outcome is by obtaining the distance from the top of the 7th index and then setting the max-height to that value.

$(document).ready(function(){
  $("ul.ul-scrollable, ol.ul-scrollable").each(function (key, val) {
    var distance = $(this).children('li').eq(7).offset().top;
    $(this).css({'max-height' : distance + 'px', 'overflow-y' : 'auto'});
  });
});
ul {
  background: white;
  width: 70px;
}
ul li {
  padding: 3px;
  margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul class="ul-scrollable" data-maxVisible="7">
<li>li1</li>
<li>li2</li>
<li>li3</li>
<li>li4</li>
<li>li5</li>
<li>li6 li6 li6</li>
<li>li7</li>
<li>li8</li>
<li>li9</li>
<li>li10</li>
<li>li11</li>
<li>li12</li>
<li>li13</li>
</ul>

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

Ensuring payload integrity using microrouter: A step-by-step guide

I have utilized this code to develop a microservice const { json, send } = require('micro') const { router, post } = require('microrouter') const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY) console.log(process.e ...

What is the best way to display changing data in a React component?

Having some trouble with printing data based on the length of an array. Here is my attempted solution, but unfortunately, it's not working as expected. I believe the issue lies in the cb function within the forEach loop. Below is the code snippet: fun ...

Tips for optimizing caching of API responses and assets using service workers in Vue CLI 3

import { register } from 'register-service-worker' import pwa from '@vue/cli-plugin-pwa' if (process.env.NODE_ENV === 'development') { // if (process.env.NODE_ENV === 'production') { console.log(pwa) register(`${pro ...

What steps can be taken to execute a function when a button remains unclicked?

$("#RunCode").click(function(){ var $this = $(this); if($this.data('clicked')) { console.log("Is clicked"); $(".documentWrite").text("Is clicked"); } else { $this.data('clicked', true); consol ...

Is the new mui LoadingButton not available in the latest version?

According to the material UI documentation found at here, you are supposed to import LoadingButton from '@material-ui/lab/LoadingButton'; However, I am unable to locate this folder within mui/lab and the import statement is resulting in an erro ...

What is the process for invoking a server-side Java function from HTML with JavaScript?

Can someone help me figure out the best way to invoke a Java method from HTML (I'm working with HTML5) using JavaScript? I attempted using Applets but that approach didn't yield any results. My goal is to extract the value from a drop-down menu i ...

I attempted to append a character to a string every two seconds, but unfortunately, it was not successful. There were no errors displayed in the console. This was done within a Vue framework

It seems like a simple task, but for some reason it's not working. I have double-checked the implementation below and everything looks fine with this.showStr += this.mainStr.charAt(i). The issue seems to be related to the connection loop and setTimer. ...

What is the best way to activate a component's function within a disabled tab using material-ui?

Currently, I am utilizing tabs from M-ui and encountered an issue when trying to incorporate a switch as one of the tabs. I made the tab non-clickable, but now the switch inside it is also not functioning. Below is the code snippet: https://codesandbox.i ...

Converting a string array to an array object in JavaScript: A step-by-step guide

My task involves extracting an array from a string and manipulating its objects. var arrayString = "[{'name': 'Ruwaida Abdo'}, {'name': 'Najlaa Saadi'}]"; This scenario arises when working with a JSON file where ce ...

The attempt to perform a Diffie-Hellman key exchange between Python and Node has hit a roadblock, as an error stating that

Currently, I am attempting to establish a DH key exchange between a Python 3.6 client and a Node server deployed in a Docker container with the latest node image (Node version: v13.10.1). On the client side, I am utilizing the cryptography.io library (v2. ...

Challenges with creating a contact form using bootstrap modal

I'm facing an issue with a bootstrap modal contact form. It works fine on all browsers except for iPad/Safari. Can anyone help me figure out what's wrong? On iPad, the modal is positioned to the right and down the page instead of in the cente ...

Displaying content using Jquery's slideDown feature, overlapping existing content

I am working on displaying one piece of content over another using Jquery slidedown as an overlay. Despite adding z-index properties, I am struggling to make it work. My goal is to have the div with class "selection_nip" appear as an overlay on top of ano ...

Creating a custom JavaScript clock based on stored database values

I am looking to create an analog clock using JavaScript. I have both working hours and off hours stored in a database. My goal is to display working hours in one color and off hours in another color on the clock. How can I achieve this? The database prov ...

Using Vuex: Delay dispatch of action until websocket response received

Let's look at the given scenario and premises: To populate a chat queue in real time, it is necessary to establish a connection to a websocket, send a message, and then store the data in a websocket store. This store will handle all the websocket sta ...

Using the spread operator to pass properties in React

Update: After delving deep into the documentation, @wawka has discovered that there may be some issues with the react-router-dom v^5.0.1 causing problems with the myLink2 component. It seems like a rewrite of this component may be necessary. In my React p ...

Leveraging font as a comprehensive repository of icons

I have been experimenting with using entypo as the icon source for my web application. The UI technology I am working with is ZK. However, I encountered an issue when trying to include an icon from that font by using: <span sclass="entypoWhite">&am ...

Utilizing Ajax to fetch a div element from a web page

Hey there! I have a link set up that loads a page into a specific div ID, which is #ey_4col3. The issue I'm facing is that it loads the entire page along with all its contents, but what I really want to load from that page is just the content within ...

Is the next function triggered only after the iframe has finished loading?

First and foremost, I understand the importance of running things asynchronously whenever possible. In my code, there exists a function known as wrap: This function essentially loads the current page within an iframe. This is necessary to ensure that Jav ...

Layer added to map by Mapbox encountered an error during the process

I encountered an error that looks like this: https://i.sstatic.net/TI4HO.png When running the following code snippet: map.on('load', function () { map.addLayer({'type': 'scattermapbox', &ap ...

Is there a way to line up these two tables or divs using a shared parent header div?

In the process of developing this webpage, I encountered a layout that resembles the following: https://i.sstatic.net/T8XHa.png Here is an approximation of the HTML structure: <div class="title"> <table> <tr> &l ...