简体   繁体   中英

Javascript auto scroll on div

I would like to scroll at the end of the div so in my case I can see the last message of chat. Here's what I have but it doesn't work, the scroll is actually on top of the div.

<script type="text/javascript">
var divChat = document.getElementById('chat');
divChat.scrollTop = divChat.scrollHeight;
</script>
<div id="chat" style="border-style:groove;overflow-y: auto; height:50%;">
<?php 
    $response = $bdd->query('SELECT * FROM minichat');
    while ($rsp = $response->fetch())
    {
        echo '['.$rsp['date_message'].']'." <strong>".htmlspecialchars($rsp['pseudo'])
        ."</strong>: ".htmlspecialchars($rsp['message'])."<br>";
    }
?>
</div>

Thanks by advance for any help,

This should work fine:

<div id="chat" style="border-style:groove;overflow-y: auto; height:50%;">
<?php 
    $response = $bdd->query('SELECT * FROM minichat');
    while ($rsp = $response->fetch())
    {
      echo '['.$rsp['date_message'].']'."         <strong>".htmlspecialchars($rsp['pseudo'])
    ."</strong>: ".htmlspecialchars($rsp['message'])."<br>";
    }
?>
</div>
...
<script type="text/javascript">
  var divChat = document.getElementById('chat');
  divChat.scrollTop = divChat.scrollHeight;
</script>
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM