I have a comment box and I am using following JS to set scroll to bottom and for it scroll down when new message is posted.
window.setInterval(function() {
var elem = document.getElementById('Commentbox');
elem.scrollTop = elem.scrollHeight;
}, 500);
It kind of works, when a new message is posted it scrolls down, but when I scroll up to look at old messages it scrolls me back down. Is there a way to prevent from that from happening?
I wouldn't use an interval function to scroll down, cause you scroll every 500 millis with your implementation. I think you have a function, that adds new messages and is called on incoming messages:
function addMessage() {
// here you add the new message to DOM
// ...
// then you can scroll down once to show the new messages
var elem = document.getElementById('Commentbox');
elem.scrollTop = elem.scrollHeight;
}
If you post the code how you add your new messages, i can help you better.
Because the correct solution was not working for me, I did something like this:
$('.your-div-class').scrollTop($('.your-div-class').height()*$('.your-div-class').height());
How I came up with the idea?
First I found the height of the div I want to auto-scroll by writing in the console of the browser:
console.log($('.your-div-class').height());
.
Then I found the scrollTop value:
console.log($('.your-div-class').scrollTop());
.
Then I put this in the console:
$('.your-div-class').scrollTop($('.your-div-class').height()*$('.your-div-class').height());
,
and found out that it only takes me half way down and realized,
$('.your-div-class').scrollTop($('.your-div-class').height()*$('.your-div-class').height());
would take me scrolled enough downwards.
If it doesn't work for you. You can use:
$('.your-div-class').scrollTop($('.your-div-class').height()*1000);
.
This should work for you just fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With