I am trying to create a web application (in php) and in that I am creating a chat box for the two type of user to communicate with each other. The chat box is shown just like WhatsApp Web and everything is working fine and the data is coming via ajax. It is made using bootstrap 4.
The problem is that when the page loads it shows older messages. It starts fetching all the messages using ajax and the content is shown but I want it to be scrolled down just like WhatsApp or any other chat box you see. I just want it to show latest message and then a person can scroll up to see older messages but it should initially load at the bottom. And if a new message arrives from ajax it should scroll down automatically to the latest message.
My Answer:
You can achieve this by using the scrollTop property of the container element. Here's an example of how you can load the container initially scrolled down:
javascript
// Get the chat container element
var chatContainer = document.getElementById('chat-container');
// Scroll the chat container to the bottom
chatContainer.scrollTop = chatContainer.scrollHeight;
// Function to scroll the chat container to the bottom when a new message arrives
function scrollToBottom() {
chatContainer.scrollTop = chatContainer.scrollHeight;
}
// Call the scrollToBottom function whenever a new message arrives via ajax
// For example, if you have a function that fetches new messages via ajax
function fetchNewMessages() {
// Fetch new messages via ajax
// Once the new messages are fetched, call the scrollToBottom function
scrollToBottom();
}
// Call the scrollToBottom function when the page loads
window.onload = function() {
scrollToBottom();
}
In this example, we first get the chat container element using `document.getElementById('chat-container')`. We then set the `scrollTop` property of the chat container to `scrollHeight` to scroll it to the bottom.
We also define a `scrollToBottom` function that scrolls the chat container to the bottom. This function can be called whenever a new message arrives via ajax.
Finally, we call the `scrollToBottom` function when the page loads using `window.onload`. This ensures that the chat container is initially scrolled down when the page loads.
Rate this post
3 of 5 based on 9130 votesComments