4

I've built a small chat div where people can chat. It works with AJAX which pulls to records and places them.

Everything is working fine except for a minor problem. Every time AJAX is called I want it to scroll the div down to the bottom. (Latest chat messages are on the bottom)

However, I can't figure out how to track if a user is already scrolling inside the chat div themselves or not.

I want to prevent the "auto scroll down" in case a user is active inside the chat.

How would I go around doing this?

HTML of the chat:

<div id="chat">
  <div id="chatoutput></div>
</div>

Javascript that makes it scroll to the bottom:

jQuery("#chat").scrollTop($("#chat")[0].scrollHeight);

2 Answers 2

4

You can disable the auto scroll down if the user once scrolled manually:

$("#chat").scroll(function() {
    autoScrollEnabled = false;
}); 

You have to check autoScrollEnabled before scrolling down though.

if (autoScrollEnabled) {
  jQuery("#chat").scrollTop($("#chat")[0].scrollHeight);
}

You could also store a DateTime value to check when the user last scrolled and enable autoScroll if that was, say, 1 minute ago.

Sign up to request clarification or add additional context in comments.

2 Comments

Love it, thank you very much :) How would you go around with the DateTime? Store it locally or database?
I would store it locally. In database it would only be relevant on a reload. But then you want to scroll at the bottom anyways.
0

Just use simple javascript method.

$(document).ready(function () {
     var objDiv = document.getElementById("chat");
     objDiv.scrollTop = objDiv.scrollHeight;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.