I have a scroll-bar in a div element and initially it\'s position is top. Whenever i add some text to the div element then the scroll-bar does not move. Is there any way, th
var messageBody = document.querySelector('#messageBody');
messageBody.scrollTop = messageBody.scrollHeight - messageBody.clientHeight;
That'd be :: messageBody.lastChild.scrollIntoView();
//for the initial scroll to bottom position.
p.s.: After the page load, this command should be called by your message handler on message update.
Here you go. Follow this concept.
$('#messages').scrollTop($('#messages')[0].scrollHeight);
#chatbox-history {
overflow: none;
position: relative;
width: 100%;
height: 200px;
border: 1px solid #ccc;
}
#messages {
overflow: auto;
position: absolute;
bottom: 0;
width: 100%;
max-height: 200px;
}
#messages div {
border: 1px solid #e2e4e3;
margin: 5px;
padding: 10px;
background: #fafafa;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chatbox-history">
<div id="messages">
<div>asdjf ;asd</div>
<div>ajsd fa ;skd f;s</div>
<div>asdjf ;akjs d;lf a;lksd fj</div>
<div>ajsd fkaj s;dlf a;ljsdl;fkja;lsd f; asd</div>
<div>Wassup?</div>
</div>
</div>
Something like this should do what you want if I understood what you want correctly.
Replace messageBody
in getElementById()
with your chat message container id.
var chatHistory = document.getElementById("messageBody");
chatHistory.scrollTop = chatHistory.scrollHeight;
This will scroll the message container to the bottom. Since scroll position is recorded in pixel and not percentage, the scroll position doesn't change as you add more elements into the container by default.
Do this after you have appended a new message into your chat message container.
Assume your html code like this.
HTML
<div id="parentDiv">
<div class="people">1</div>
<div class="people">2</div>
<div class="people">3</div>
<div class="people">4</div>
<div class="people">5</div>
<div class="people">6</div>
<div class="people">7</div>
<div class="people">8</div>
<div class="people">9</div>
</div>
And then wrap your js like this
JS
var objDiv = document.getElementById("parentDiv");
objDiv.scrollTop = objDiv.scrollHeight;
DEMO