skip to Main Content

I’m trying to auto scroll to bottom by this method, but this is not working. i made a ul li from JavaScript. I want to scroll it to bottom. on button click its not working.

  io.on("new_message",function(data){
    console.log(data);
    var html ="";
    if(data.sender==sender)
    {
      html+= "<li class='liRight'>"+data.msg+"</li> ";
    }
    else{
      html+= "<li class='lileft'>"+data.msg+"</li> ";
    }
    
    messagelist.innerHTML+=html;
    Scrollltobottom ();
   })

   function Scrollltobottom ()
   {
    console .log("scroll fiucvtiopjhn");
    messagelist.scrollTop = messagelist.scrollHeight;
   }

2

Answers


  1. Use scrollIntoView. Here is a minimal reproducable example

    const ul = document.createElement(`ul`);
    [...Array(250)].forEach( (_, i) => 
      ul.insertAdjacentElement(
        `beforeend`, 
        Object.assign(document.createElement(`li`), {textContent: `li ${i}`}) )
    );
    document.body.appendChild(ul);
    document.querySelector(`ul li:last-child`).scrollIntoView();
    Login or Signup to reply.
  2. const ul = document.createElement(`ul`);
    [...Array(250)].forEach( (_, i) => 
      ul.insertAdjacentElement(
        `beforeend`, 
        Object.assign(document.createElement(`li`), {textContent: `li ${i}`}) )
    );
    document.body.appendChild(ul);
    
    
    //--set id of ul
    
    function scrollToBottom(){
    let getMainDiv = document.querySelector('ul')
    getMainDiv.scrollTo(0 , getMainDiv.scrollHeight)
    }
    ul{
    background:lightgreen;
    height:300px;
    width:300px;
    overflow:auto;
    position:relative;
    }
    
    button{
    position:absolute;
    bottom:1rem;
    right:1rem;}
    <button onclick="scrollToBottom()">go to down</button>

    enter code here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search