Chat Interface Auto-Scroll Not Working – Need Help!

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:
:point_right: [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

Hi Mabelle,

You might want to try a Javascript forum.
In general, you can add console logs to determine if/when your mutation observer is firing and what it’s seeing.

Your chat not auto-scrolling is likely due to timing issues or the container not fully rendering before the scroll executes. Ensure #chat-messages has a set height with overflow: auto or scroll. Modify scrollToBottom to use setTimeout(() => chatContainer.scrollTo({ top: chatContainer.scrollHeight, behavior: "smooth" }), 100); for a smoother effect. Also, check if new messages are inside another wrapper—if so, update the MutationObserver selector. Try these fixes and republish—if you need further help, feel free to contact me.

I tried everything it is not working i can’t understand why.

Canyou please assist