theUnforgiven's avatar

Vue scroll to bottom of div

Hey all,

Hope everyone is good and still safe....

I have a small issue I can't figure out. I want upon clicking an accordion it expands and shows a chat log.

Code for this is as follows:

<div class="panel-body chat-panel border border-light border-bottom-0">
                        <ul class="list-unstyled">
                            <li class="media" v-for="(conversation,index) in group.messages" :key="index" :class="`collapse-${group.id}`">
                                <i class="far fa-user mr-3 img-thumbnail"></i>
                                <div class="media-body" ref="chat">
                                    <h5 class="mt-0 mb-1">
                                        {{ conversation.user.name }}
                                    </h5>
                                    <p>
                                        {{ conversation.message }}<br />
                                        <small class="text-muted pt-1">{{ human(conversation.updated_at) }}</small>
                                    </p>
                                </div>
                            </li>
                        </ul>
                    </div>

This has a set height on the chat-panel class so upon the user clicking to show this I want the list to scroll to the bottom where the latest message is displayed.

I have tried the following:

this.$refs.chat.scrollIntoView();

// Which the ref is on 
<div class="media-body" ref="chat">

But it fails to scroll, what am I missing or doing wrong?

0 likes
6 replies
bobbybouwmann's avatar

The problem here is that the chat ref is already in the view. Because the first item also has the ref="chat", just like the last item.

You need to have a unique ref for the last item. You can check if the current item is the last item and add an extra ref.

Another solution is putting a ref on the div that is wrapped around all the list items. For example, the div or the ul in your case. Check this out: https://stackoverflow.com/questions/40730116/scroll-to-bottom-of-div-with-vue-js

1 like
bobbybouwmann's avatar

So like I said before, the element is already in the view because it's a long list. You need to scroll to the bottom of the element instead of scroll into view. Did you check the link I send you?

1 like
theUnforgiven's avatar

Yes, I had already tried that option too of:

 var messageDisplay = this.$refs.chat;
messageDisplay.scrollTop = messageDisplay.scrollHeight;

But again to no avail :(

theUnforgiven's avatar

Even with this:

var div = document.getElementById("collapse-" + group.id);
div.scrollTop = div.scrollHeight - div.clientHeight;

Then I have on the parent div

<div :id="`collapse-${group.id}`" class="collapse" aria-labelledby="headingOne" data-parent="#accordionExample">

with the bind ID been unique each time. Again still the list of messages stay at the top.

Please or to participate in this conversation.