You can remove the $('#chat_button) , no problem, but leave it as it is.
The key here is to determine if the bottom is scrolling, then load more content, and then move the scroll, if earlier below.
$(document).ready(function(){ var out, isScrolledToBottom; out = document.getElementById("chat-feed"); // outer container of messages $('#chat_button').click(function(){ isScrolledToBottom = checkIfScrolledBottom(); $.ajax({ url:"insert.php" }).done(function() { scrollToBottom(isScrolledToBottom); }); }); // initial load of chat $('#chat-feed').load("chat-feed.php", function() { out = document.getElementById("chat-feed"); // re-reference after a jQuery .load() as it removes the original dom element and add a new one scrollToBottom(true); }); // check for chatter every second setInterval(function() { isScrolledToBottom = checkIfScrolledBottom(); $('#chat-feed').load("chat-feed.php", function() { out = document.getElementById("chat-feed"); // re-reference after a jQuery .load() as it removes the original dom element and add a new one scrollToBottom(isScrolledToBottom); }); }, 1000); function checkIfScrolledBottom() { // allow for 1px inaccuracy by adding 1 return out.scrollHeight - out.clientHeight <= out.scrollTop + 1; } function scrollToBottom(scrollDown) { if (scrollDown) out.scrollTop = out.scrollHeight - out.clientHeight; } //setTimeout(function() { $("#chat-feed").scrollTop($("#chat-feed")[0].scrollHeight);}, 1200); });
source share