Search code examples
javascripthtmlcssscrollbaroverflow

Automatic scrolling for CSS overflow: scroll


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>"

Solution

  • 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>