简体   繁体   中英

How to Scroll to bottom of div (chat) - synchronously

I'm trying to create a chat application. Every time the user sends a new message, the new message gets appended to a ul list of messages. I have made the UL list scrollable and it is scrolling overtime I send a message; however it is not scrolling all the way to the bottom. FYI: I'm using Vue.js

This is current code:

this.messages.push(this.currentMessage) //adding new message to the list
var div = document.getElementById('chat-list-ul');
div.scrollTop = div.scrollHeight;

It somehow just scrolls to one line before the bottom. Doing some testing I discovered that it maybe caused by the scroll function being called too fast, because if I insert a timeout of 1s, it will scroll correctly.

My question is: is there a way to create a promise for the array.push() function that will allow me to call the scroll method only after the array has gotten update with the new value?

Thank you,

You can use Vue.nextTick(callback) to wait for the DOM to be updated after pushing the new message before you trigger the scroll. Something like this ..

this.messages.push(this.currentMessage) //adding new message to the list
Vue.nextTick(function () {
    var div = document.getElementById('chat-list-ul');
    div.scrollTop = div.scrollHeight;
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM