so basicaly, i'm doing a chat in vuejs + socket.io and I want that every time a message is sent, received, or when you come to the site, you arrive directly to the bottom of the page, where the latest message is
I've done a function that fires on the onMounted hook, when I retrieve the data, and on the socket.on('message') :
const scrollToLatest = () => {
let container = document.getElementById("messages")
console.log("scrolltop",container.scrollTop)
console.log("scrollheight",container.scrollHeight)
container.scrollTop = container.scrollHeight;
console.log("scrolltop after", container.scrollTop)
}
Here are what the console.log returns :
(if you can't load the image :)
scrolltop 0
scrollheight 5594
scrolltop after 0
I've tried to use window.scrollTo(0, container.scrollHeight) but it doesn't work either
I hope that someone will be able to help me, I've searched a lot on this issue, but I wasn't able to make it work properly
pass a custom class to your div in your <template> first:
<div :class="`messages`">
</div>
and then get the position of the div as a number:
getPositionOfElement() {
return (document.getElementsByClassName("messages").getBoundingClientRect().top - window.innerHeight);
}
This would be the method for scrolling to the position where your div is located - adapt it to your needs as described in the official documentation:
smoothScroll(vertPos) {
window.scrollTo({
top: vertPos,
left: 0,
behavior: 'smooth'
});
}
combine both methods like this from the place where you need to perform the scrolling - calling this either from another method or directly from the template...
this.smoothScroll(this.getPositionOfElement());
Please let me know if this works for you.