Hello everyone,
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:
[My Webflow Project]
https://preview.webflow.com/preview/mabelles-ultra-awesome-site?utm_medium=preview_link&utm_source=designer&utm_content=mabelles-ultra-awesome-site&preview=a3416b477281c47b3ec6738f543b0ebe&pageId=6702d4ad3e204f6ee8635e93&locale=en&workflow=preview
Can someone please help me troubleshoot this? Thanks