slidefizz
slidefizz

Reputation: 267

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,

Upvotes: 0

Views: 3240

Answers (1)

Alexandre Nicolas
Alexandre Nicolas

Reputation: 1949

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>

Upvotes: 1

Related Questions