0

I have a script that scrolls to the bottom of the messages div when it loads the chat or when a new message is sent. I was checking if the user was already at the bottom of the div because if it is not... I don't want to push it to the bottom of that div every time the system checks for a new message but I can't get this to work... why? When the system reloads the messages... the user is no longer at the bottom of the div so it doesn't scroll automatically..

I am trying to determine if a user is at the bottom of a div even when a new message comes in... but as soon as a new message is added to the messages div [this code states that wow this user is no longer at the bottom] then it doesn't scrolls to the bottom anymore... I need somehow to save the previous position of that user and then when a new message is added... check if user is in the same position then scrolls to the bottom too!!

function loadMensagens(scroll = false) {
    jQuery.ajax({
        method: "POST",
        url: "/api/",
        data: {action: "getMensagem", id: "<?=(isset($url[1]) ? $url[1] : 0)?>"}
    }).done(function (r) {
        jQuery("#chatScroll").html(r);
        let divElement = document.getElementById('chatScroll');
        if ((divElement.scrollHeight - divElement.scrollTop === divElement.clientHeight) || scroll) {
            divElement.scrollTop = divElement.scrollHeight;
        }
    });
}

//end loadAllAnexos     loadMensagens(true); 
// first load     setInterval(loadMensagens, 4000);
1
  • So you want to scroll to the bottom automatically only when a new message arrives? Commented Jul 5 at 4:40

1 Answer 1

0

Try Storing the user scroll position before updating the chat then, check if the user was at the bottom before the update and only scroll if they were.

I updated your code

function loadMensagens(scroll = false) {
    let divElement = document.getElementById('chatScroll');
    
    // Check if the user is at the bottom
    let wasAtBottom = (divElement.scrollHeight - divElement.scrollTop === divElement.clientHeight);
    
    jQuery.ajax({
        method: "POST",
        url: "/api/",
        data: {action: "getMensagem", id: "<?=(isset($url[1]) ? $url[1] : 0)?>"}
    }).done(function (r) {
        jQuery("#chatScroll").html(r);
        
        // Check if the user was at the bottom before the update or if it's the initial load
        if (wasAtBottom || scroll) {
            divElement.scrollTop = divElement.scrollHeight;
        }
    });
}

// First load with scroll to bottom
loadMensagens(true);

// Subsequent loads without forcing scroll to bottom
setInterval(loadMensagens, 4000);
New contributor
Ugwu Somto is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
1
  • Thanks a lot @Ugwu Somto, it worked as expected!!! Commented 2 days ago

Not the answer you're looking for? Browse other questions tagged or ask your own question.