Generally we create a div with the content and dynamically update the content. Further, we want to maintain the scroll position according to updated content. So there is one question of how to set scroll position to bottom in a div using JavaScript. Same type of problem I faced few days ago when I was working with a ajax message application and I am trying to get a div to scroll to the bottom when chat is updated. The HTML was as below:
1 2 3 | <div id="messagebox" class="messagebox"> //content would be here </div> |
How to set scroll position to bottom in a div
This div has a fixed height with overflow: scroll
so that when we get more content than height, it would automatically get scroll bar there. We can write code to get bottom scroll position in a div by various way but logic would be the same which is
- Get the height of div and
- Then set to scroll position according to that scroll height
1 2 3 | //By jQuery scrollTop $("#messagebox").scrollTop($("#messagebox")[0].scrollHeight); |
1 2 3 4 | //By JavaScript: var msgDiv = document.getElementByClass("messagebox"); msgDiv.scrollTop = msgDiv.scrollHeight; |
1 2 3 4 5 | //By JQuery animate : $('#messagebox').stop().animate({ scrollTop: $("#messagebox")[0].scrollHeight }, 800); |
By using either of these 3 ways, we can easily set the scroll position to bottom in a div which is updated with content dynamically. If you have any query regarding the article, you are most welcome with your comments.