Reputation: 2395
I have div with fixed width and height. Div contains unordered list and has css overflow-y: scroll
property. In javascript I have function which triggers when user click button below list, and that function adds one list item. When there is too much content inside div, new list items are added at the bottom of list and user needs to scroll list in order to see new list items. Is it possible somehow to make scroll bar auto scroll along with new content added, so that last added list item would be always visible?
Html:
<ul id="scroll">
<li>a</li>
<li>b</li>
<li>c</li>
</ul>
<button type="button" id="click">Click</button>
Css:
ul {
height: 100px;
width: 100px;
overflow-y: scroll;
border: 1px solid black;
}
Javascript:
function addListItem(){
var message = document.createElement('li');
message.innerHTML = 'd';
document.getElementById('scroll').appendChild(message);
}
document.getElementById('click').addEventListener('click', addListItem, true);
JS fiddle link: https://jsfiddle.net/8gjhatvt/2/
Upvotes: 3
Views: 13644
Reputation: 1
Add this code to addListItem() function:
var scroll=document.getElementById("scroll");
scroll.scrollTop = scroll.scrollHeight;
Upvotes: 0
Reputation: 149
Set the Element.scrollTop property of the scrolling div to be the position of the new element in the page + the new element's offset in its parent.
For example in the addListItem() function add the following line:
document.getElementById('scroll').scrollTop = message.offsetHeight + message.offsetTop;
Working fiddle: https://jsfiddle.net/rvnj6mc3/
Upvotes: 1