A few days ago I asked how can I keep my scroll bar at the bottom when new data comes in. I got this answer which worked perfectly fine for me. But now I have a new requirement.
You can figure out if you are scrolled to the bottom like this
var isScrolled = (element.scrollHeight - element.scrollTop === element.clientHeight);
then:
if (isScrolled) {
//code here to move scrollbar down
}
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight
For this you might need a flag. So what I am doing is:
Not sure why it isn't work. I have got the script I was working here.
$(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);
var scr = setInterval(function() {
var element = document.getElementById("conversationDiv");
element.scrollTop = element.scrollHeight;
}, 500);
$("#conversationDiv").scroll(function () {
var element = document.getElementById("conversationDiv");
if ((Number(element.scrollTop) + Number($(element).height())) != (Number(element.scrollHeight)))
clearInterval(scr);
else
if (element.scrollTop < element.scrollHeight)
scr = 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>
Looks like something is missing. I am almost near it. Should something be there in the area of Number(element.scrollTop)
, Number($(element).height())
, Number(element.scrollHeight)
.