I am making a chat where, on load, the scrollbar scrolls to the bottom. This is the JS function that gets called on load:
<script>
function updateScroll() {
var element = document.getElementById("chatlogs");
var elementHeight = element.scrollHeight;
element.scrollTop = elementHeight
}
window.onload = updateScroll;
</script>
Then, with this code:
$(document).ready(function(e) {
$.ajaxSetup({cache:false});
setInterval(function() {$('#chatlogs').load('logs.php');}, 1000);
});
..the chat gets updated every second. What happens though, is that when it updates, the scrollbar goes to the middle, instead of remaining at the bottom. How can I make my chat stay at the bottom, when the last code makes the chat refresh?
You can see a working example here: http://www.friendsinclass.co.nf/ Please let me know, thank you!
A couple thoughts, first you'll probably want to use recursion to call the AJAX request on AJAX success. Using
setInterval()
could result in any number of AJAX requests happening at any given time, depending on how long they take to return.Second, to prevent the scroll bar from jumping to the bottom if the user has scrolled, you'll probably want to give them a notice and the ability to jump to the bottom if there is new content.
Considering those points, something like this would work:
JavaScript
HTML
CSS
JS Fiddle example https://jsfiddle.net/igor_9000/9tbrgrkn/3/ with a test AJAX endpoint
Hope that helps!