Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
148
rated 0 times [  149] [ 1]  / answers: 1 / hits: 143622  / 10 Years ago, tue, august 26, 2014, 12:00:00

I have this code, to load chat



function getMessages(letter) {
var div = $('#messages');
$.get('msg_show.php', function (data) {
div.html(data);
});
}

setInterval(getMessages, 100);


What I have to add, to automatically scroll down #messages div on page load, and again with every new chat post?



This doesn't work:



function getMessages(letter) {
var div = $('#messages');
$.get('msg_show.php', function (data) {
div.html(data);
$('#messages').scrollTop($('#messages')[0].scrollHeight);
});
}

setInterval(getMessages, 100);

More From » jquery

 Answers
0

Let's review a few useful concepts about scrolling first:





When should you scroll?




  • User has loaded messages for the first time.

  • New messages have arrived and you are at the bottom of the scroll (you don't want to force scroll when the user is scrolling up to read previous messages).



Programmatically that is:



if (firstTime) {
container.scrollTop = container.scrollHeight;
firstTime = false;
} else if (container.scrollTop + container.clientHeight === container.scrollHeight) {
container.scrollTop = container.scrollHeight;
}


Full chat simulator (with JavaScript):



https://jsfiddle.net/apvtL9xa/





const messages = document.getElementById('messages');

function appendMessage() {
const message = document.getElementsByClassName('message')[0];
const newMessage = message.cloneNode(true);
messages.appendChild(newMessage);
}

function getMessages() {
// Prior to getting your messages.
shouldScroll = messages.scrollTop + messages.clientHeight === messages.scrollHeight;
/*
* Get your messages, we'll just simulate it by appending a new one syncronously.
*/
appendMessage();
// After getting your messages.
if (!shouldScroll) {
scrollToBottom();
}
}

function scrollToBottom() {
messages.scrollTop = messages.scrollHeight;
}

scrollToBottom();

setInterval(getMessages, 100);

#messages {
height: 200px;
overflow-y: auto;
}

<div id=messages>
<div class=message>
Hello world
</div>
</div>




[#69657] Friday, August 22, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jacquezf

Total Points: 27
Total Questions: 109
Total Answers: 98

Location: Lesotho
Member since Wed, Jun 2, 2021
3 Years ago
;