Search code examples
javascriptjquerycsschatautoscroll

autoscroll javascript function in chatbox


how do i achieve a scroll down on my chatbox, because i cant see the realtime message. i want it to be called on my div id where my i put my style overflow

<script>
  //scroll to bottom
  window.onload=toBottom;
  function toBottom(){
    window.scrollTo(0, document.body.scrollHeight);
  }//end of scroll to bottom
</script>

view part

<div class="scrollMessage w3-padding div" onload="toBottom" id="scroll" style="overflow-y:scroll;height: 460px;">
      <?php include 'getMessage.php'; ?>        
</div>

at first load it should already be on the last message

at actual chat conversation it will also be on the last message to show


Solution

  • This is what you're looking for. Hope, it helps.

    var objDiv = document.getElementById("scroll2"); //Obtain the ID of the chat div
    window.onload = toBottom;
    function toBottom() {
      objDiv.scrollTop = objDiv.scrollHeight; //Set the scroll offset position to the height of the chat div
    }
    <div id="scroll">
    <div class="scrollMessage w3-padding div" onload="toBottom" id="scroll2" style="overflow-y:scroll;height: 200px;width:150px;">
      <!--<?php include 'getMessage.php'; ?>-->
      Random messages <br>
      Random messages <br>
      Random messages <br>
      Random messages <br>
      Random messages <br>
      Random messages <br>
      Random messages <br>
      Random messages <br>
      Random messages <br>
      Random messages <br>
      Random messages <br>
      Random messages <br>
      Random messages <br>
      Random messages <br>
      Random messages <br>
      Random messages <br>
      Random messages <br>
      Random messages <br>
    </div>
    </div>