Page 1 sur 1

Chat Interface Auto-Scroll Not Working – Need Help!

Posté : 05 févr. 2025, 14:31
par Donottouch
Hello everyone,
I am creating a website on webflow
I created a chat interface where each message appears with a 2-second delay, and I set the container to overflow: auto so users can scroll. Now, I want to make the chat auto-scroll to the latest message whenever a new one appears. Please use the tablet version to understand, the interface is in the 2nd section of the page

I added the following JavaScript code:

html

CopierModifier

<script>
document.addEventListener("DOMContentLoaded", function() {
var chatContainer = document.getElementById("chat-messages");

if (!chatContainer) {
console.error("The element #chat-messages does not exist!");
return;
}

function scrollToBottom() {
requestAnimationFrame(() => {
chatContainer.scrollTop = chatContainer.scrollHeight;
});
}

// Observe the addition of new messages with the class "message"
var observer = new MutationObserver(function(mutations) {
let newMessageAdded = false;
mutations.forEach(function(mutation) {
mutation.addedNodes.forEach(function(node) {
if (node.nodeType === 1 && node.classList.contains("message")) {
newMessageAdded = true;
}
});
});

if (newMessageAdded) {
setTimeout(scrollToBottom, 100); // Small delay to allow rendering
}
});

observer.observe(chatContainer, { childList: true, subtree: true });

// Initial scroll to the bottom when the page loads
setTimeout(scrollToBottom, 300);
});
</script>
However, this code is not working. The chat does not scroll when new messages appear.

Here is my Read-Only link:
:point_right: [My Webflow Project]
https://preview.webflow.com/preview/mab ... ow=preview

Can someone please help me troubleshoot this? Thanks