Furman Furman - 1 year ago 146
CSS Question

Css scroll bar auto scrolling with added content

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?


<ul id="scroll">
<button type="button" id="click">Click</button>


ul {
height: 100px;
width: 100px;
overflow-y: scroll;
border: 1px solid black;


function addListItem(){
var message = document.createElement('li');
message.innerHTML = 'd';


document.getElementById('click').addEventListener('click', addListItem, true);

JS fiddle link: https://jsfiddle.net/8gjhatvt/2/

Answer Source

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/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download