TrexCodes
TrexCodes

Reputation: 87

How to automatically scroll to the bottom of div when a new message / element is created

I want to scroll to the bottom of the page when a user posts a new message, when a new message is posted it creates a element that looks like this (the code is in jinja2 format, but that doesnt really matter, basically what I am doing is styling the messages, and getting previous messages from my database, if any, and displaying them using a for loop),

<div class="container">
    <div class="jumbotron" id="messages">
        <div class="message_holder">
            {% if previous_chat %}
            {% for i in previous_chat %}
            <div style="margin-bottom: 10px; padding: 15px;" class="msg">
                <span>
                    <img src="{{ url_for('static', filename='images/nyan.gif') }}" height="32" width="32"
                        style="border-radius: 50%;">
                    <b style="margin-left: 8px; font-size: 18px; vertical-align: middle;">{{ i.user.username }}</b>
                </span>
                <code style="margin-left: 5px; display: none;"
                    class="time-posted">{{ i.created_date.strftime("%d %B %Y %X") }} GMT</code><br>
                <span style="margin-left: 40px;">{{ i.message }}</></span>
            </div>
            {% endfor %}
            {% endif %}
        </div>
    </div>
</div>

This is my current javascript to do so, but it only works on page refresh and not when a new element is created (i tried using a while loop to continuously go to the bottom of the messages, but it just hangs the site)

$("#messages").ready(function () {
  $("#messages").scrollTop($("#messages")[0].scrollHeight);
});

This is the CSS for the message jumbotron

#messages {
  overflow-y: scroll;
  margin-top: 3rem;
  margin-bottom: 1rem;
  height: 75vh;
  border: 2px solid gray;
  padding: 25px;
  border-radius: 5px;
}

Thanks in advance!

Upvotes: 1

Views: 2245

Answers (1)

Aryan
Aryan

Reputation: 1113

Here is your solution, it is kind of brute force, but best you can do without any external libraries

function updateScroll() {
  var element = document.getElementById("messages");
  element.scrollTop = element.scrollHeight;
}
setInterval(updateScroll, 100); // Update every 100 ms (almost unnoticed)

Upvotes: 1

Related Questions