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: /
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/8gjhatvt/2/
Share asked Aug 11, 2016 at 20:33 FurmanFurman 2,4635 gold badges37 silver badges52 bronze badges2 Answers
Reset to default 1Set 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/rvnj6mc3/
Add this code to addListItem() function:
var scroll=document.getElementById("scroll");
scroll.scrollTop = scroll.scrollHeight;