-1

I am working on a chat application and I have a background where the messages should be displayed. To not just have simple overflow I added this line to css: overflow-y: scroll; which will add a scroll bar. This all works fine, but is there a way to automatically scroll to the bottom, where the newest messages are. It can also be in JavaScript.

My html code looks like this:

<article id="chat">
    <script src="chat.js"></script>
</article>

Each message will have this form and gets added into the article:

"<p class='msg'>" + msg + "</p>"
user11914177
  • 885
  • 11
  • 33
  • Have a look at [`window.scrollBy`](https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollBy) – Wais Kamal Jun 09 '20 at 09:56
  • https://stackoverflow.com/questions/11715646/scroll-automatically-to-the-bottom-of-the-page – kurumkan Jun 09 '20 at 09:59
  • I don't really get what I should do, I made this code: `window.scrollTo(0, document.querySelector("#chat").scrollHeight);` but it doesn't work – user11914177 Jun 09 '20 at 10:02

2 Answers2

1

Snippet changed:

var targetElm = document.querySelector('.boxChild'),  // reference to scroll target
    button = document.querySelector('button');        // button that triggers the scroll
  
// bind "click" event to a button 
button.addEventListener('click', function(){
   targetElm.scrollIntoView()
})
.box {
  width: 80%;
  border: 2px dashed;
  height: 180px;
  overflow: auto;
  scroll-behavior: smooth; /* <-- for smooth scroll */
}

.boxChild {
  margin: 600px 0 300px;
  width: 40px;
  height: 40px;
  background: green;
}
<button>Scroll to element</button>
<div class='box'>
  <div class='boxChild'></div>
</div>
SoliMoli
  • 781
  • 2
  • 6
  • 25
  • 1
    Your post will be much improved if you could provide a code example or add additional details what OP should. Right now you only refer to a different post, which is basically a comment. – Emiel Zuurbier Jun 09 '20 at 10:00
  • I don't really get what I should do, I made this code: `window.scrollTo(0, document.querySelector("#chat").scrollHeight);` but it doesn't work – user11914177 Jun 09 '20 at 10:02
  • I tried a test so you can find something,... is that useful? – SoliMoli Jun 09 '20 at 10:05
  • Well it is working on your example, but it doesn't work on mine. It scrolls down the whole page, but it doesn't scroll down my chat article – user11914177 Jun 09 '20 at 10:07
  • OK, i changed the snippet now your element should scrolls not the whole page. let me know if worked for you. – SoliMoli Jun 09 '20 at 10:30
1

I had to change up the answer from "so hell" a bit, since his answer only works with one message. I give every message an unique id and then scroll to that id with this command:

document.querySelector("#msgid" + msgId).scrollIntoView();
user11914177
  • 885
  • 11
  • 33
  • I mean I already had that kind of idea but hoped that there is a more elegant solution. But you can use the Reputation – user11914177 Jun 09 '20 at 11:14