Reputation: 6285
I have this code:
<div id="conversationDiv" style="overflow:auto">
<label>What is your name?</label><input type="text" id="name" />
<button id="sendName" onclick="sendName();updateScroll();">Send</button>
<p id="response"></p>
</div>
And I have this javascript function which I run after I click on 'Send' button and it keeps running after 1 second interval.
<script type="text/javascript">
function updateScroll() {
setInterval(function(){ var element = document.getElementById("conversationDiv");
element.scrollTop = element.scrollHeight; }, 1000);
}
</script>
This is my sendName() function if anyone wants to see:
function sendName() {
var name = document.getElementById('name').value;
stompClient.send("/app/hello", {}, JSON.stringify({ 'name': name }));
}
But the problem is, my scroll bar is never at the bottom.
I am running a Websocket connection and the information keeps coming and coming and when information is enough for scroll bar to appear, I don't want it to go up. I would like it to stay at bottom unless a user scrolls back up him/herself. I don't know why my code is not working. Any help is appreciated. Thanks
Upvotes: 0
Views: 186
Reputation: 167250
You are setting a timer using setInterval()
. Either change your code to:
function updateScroll() {
var element = document.getElementById("conversationDiv");
element.scrollTop = element.scrollHeight;
}
Or just add one simple code in document
's ready
event:
setInterval(function() {
var element = document.getElementById("conversationDiv");
element.scrollTop = element.scrollHeight;
}, 1000);
Unless I myself scroll up...
Okay, here's the tricky bit. You might consider adding a flag
to the timer, so that when the scroll is made on the top direction, you can clear the timer.
The full code...
$(function () {
var count = 1;
setInterval(function () {
$("#conversationDiv").append('<p>Message #' + count++ + ': Lorem ipsum dolor sit amet, consectetur adipisicing elit. Praesentium repudiandae doloribus unde, repellat maiores minus fuga earum esse, ab, aperiam voluptatibus est dolorem placeat perferendis omnis libero dolore alias quasi!</p>');
}, 1000);
setInterval(function() {
var element = document.getElementById("conversationDiv");
element.scrollTop = element.scrollHeight;
}, 500);
});
* {font-family: 'Segoe UI'; margin: 0; padding: 0; list-style: none;}
#conversationDiv {height: 350px; overflow: auto; border: 1px solid #ccc;}
#conversationDiv p {margin: 5px 5px 10px; padding: 5px; border: 1px solid #ccc; background-color: #f5f5f5;}
<script src="https://code.jquery.com/jquery-2.1.4.js"></script><div id="conversationDiv">
</div>
Upvotes: 1