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.