How can I auto scroll down - chat app with django

hello I want to auto scrolldown because whenever I refresh the page I see always the top of conversations I mean the start-conversation , this is my code

<div class="card-body height3 scrollbar" style="margin-bottom: -60px;" id="card-body">
            
                    <ul class="chat-list" id="chat-list-id">
                        <p class="start-conversation">&nbsp;</p>
                        {% for chat in chats %}
                            {% if chat.from_user == user.username %}
                                <li class="out">
                                    <div class="chat-img">
                                        <img alt="avatar" style="height: 48px;width: 48px;" src="{{here.image.url}}">
                                    </div>
                                    <div class="chat-body">
                                        <div class="chat-message">
                                            <h5>Me</h5>
                                            <p>{{chat.messag_body}}</p>
                                        </div>
                                    </div>
                                </li>       
                            {% else %}
                                <li class="in">
                                    <div class="chat-img">
                                        <img alt="avatar" src="{{here.image.url}}">
                                    </div>
                                    <div class="chat-body">
                                        <div class="chat-message">
                                            <h5>{{ chat.from_user }}</h5>
                                            <p>{{ chat.messag_body }}</p>
                                        </div>
                                    </div>
                                </li>
                            {% endif %}
                        {%endfor%}
                    </ul>
                </div>

You can use the scrollTop function in jQuery. So like this:

$('.chat-body').scrollTop($('.chat-body')[0].scrollHeight);

try this at the bottom of your page

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
        $('document').ready(function() {
           $('html').animate({scrollTop: document.body.scrollHeight},1);
        });
</script>
Back to Top