I have a ul defined like
<div>
<ul id="mylist">
</ul>
</div>
In my javascript I add li items to this ul with jquery using
$("mylist").append("<li>Test</li>");
I want my ul to automatically scroll down the div to when I have added a lot of li items and ul surpass the height defined for it
Things I have tried:
A: You can try to add the scroll bar for submenu manually. For this purpose you should open your page where you added the css3menu in any text editor and add class="scroll" into the <ul></ul> tag. You can also change the value of 'max-height' parameter.
To scroll to the bottom of a div , set the JavaScript scrollTop property of the element to the value of its scrollHeight property.
use css position top keep it at the bottom {position : relative; bottom:0;} . Remove the css property once the user has scroll.
The scrollIntoView method: The scrollIntoView() is used to scroll to the specified element in the browser. Example: Using scrollIntoView() to scroll to an element.
This can be done also in Vanilla JS no need for JQuery:
items = document.querySelectorAll(".dummy");
last = items[items.length-1];
last.scrollIntoView();
See also snippet below:
//this adds the new element at the bottom
button = document.querySelector("button")
button.onclick = function() {
list = document.querySelector("#mylist");
var li = document.createElement("li");
li.textContent = "Added with Vanilla JS"
list.appendChild(li);
//this jumps to the last element on the bottom
items = document.querySelectorAll(".dummy");
console.log(items);
last = items[items.length-1];
last.scrollIntoView();
}
#mylist {
max-height: 200px;
overflow-y: auto;
}
.dummy {
min-height: 80px;
background-color: lightgrey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button>Add</button>
<div>
<ul id="mylist">
<li class="dummy">Test</li>
<li class="dummy">Test</li>
<li class="dummy">Test</li>
<li class="dummy">Test</li>
<li class="dummy">Test</li>
</ul>
</div>
Click this JS fiddle. It will help you.
Jquery:
$('.add').click(function(){
$("#mylist").append("<li>Test</li>");
$('#mylist').animate({scrollTop: $('#mylist').prop("scrollHeight")}, 500);
});
Html:
<div>
<ul id="mylist"></ul>
<button class="add">Add li</button>
</div>
Css:
#mylist {
width: 100px;
height: 200px;
padding: 20px;
background-color: #eeeeee;
overflow-y: auto;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With