Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll down to bottom when new message is sent

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?

like image 494
DN0300 Avatar asked Mar 12 '23 14:03

DN0300


2 Answers

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.

like image 176
Sim Avatar answered Mar 15 '23 23:03

Sim


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?

  1. 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());.

  2. Then I found the scrollTop value:

    console.log($('.your-div-class').scrollTop());.

  3. 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.

like image 32
Nahid Islam Shaiket Avatar answered Mar 15 '23 23:03

Nahid Islam Shaiket