I am writing a VueJS App with Ionic. The App also has a Chat. Obviously, you want to see the lastest message, not the oldest one, so the app needs to open with the container scrolled to the bottom (also, every time you get a new message, you want it to appear at the bottom).
My HTML-Template (parts):
<ion-content
:scroll-events="true">
<ion-grid>
<ion-row v-for="(message, index) in messages" v-bind:key="index"
:id="(index === messages.length-1)? 'bottomMessage': 'notLastMessage'">
<ion-col
size="9"
:offset="message.fromUsrName === user.name ? 3 : 0 "
:class="
message.fromUsrName === user.name
? 'my-message'
: 'other-message'
"
>
<b>{{ message.fromUsrName }}</b
><br/>
<span>{{ message.text }}</span>
<div class="time">
{{ new Date(message.timestamp).toLocaleString() }}
</div>
</ion-col>
</ion-row>
</ion-grid>
</ion-content>
I tried the following:
const element = document.querySelector('ion-grid')
element.scrollTop = element.scrollHeight;
document.querySelector('ion-content').scrollToBottom(0);
const messageDiv = document.getElementById('bottomMessage')
if (messageDiv) {
messageDiv.scrollIntoView({behavior: "smooth"});
} else {
console.log("no messageDiv");
}
and the suggested answer here: Scroll to bottom of div?
EDIT: I also tried what @Phil0xFF suggested:
scrollToBottom: function () {
console.log("scrollToBottom");
const element = document.getElementById('content');
if (element) {
element.scrollToBottom(0);
console.log("scrolled");
} else {
console.log("no div");
}
}
and the console shows the following:
scrollToBottom Chat.vue:171
scrolled Chat.vue:175
scrollToBottom Chat.vue:171
scrolled Chat.vue:175
EDIT END
None of that works, it refuses to scroll at all. I also don't get any error message, I also verified, that the document.querySelector (and the document.getElementById) actually find the element.
Since my data is loaded asynchronously, I also tried working with a timeout of 2 sec, to ensure that the data was loaded.
I would be grateful, if anyone has an idea on what I am missing or another great way of implementing my use case.
(I am starting to question my intelligence, this is quite a common use case, ain't it?)