synaptik synaptik - 2 months ago 5x
HTML Question

Scroll to bottom of page when new content added (no AJAX involved)

I have a PHP script, which I cannot modify, that executes some commands on a linux machine and pipes stdout and stderr to the webpage. When the PHP page is requested, it keeps loading until all the commands have finished. Output appears on the page as it is generated on the linux machine.

Currently, when new content is added, it will (eventually) be added below the view on the page such that I have to scroll down manually in order to see it. I'm looking for a way to keep the page scrolled to the bottom, or to scroll whenever new content is added.

Any ideas?

Note: I have tried

$('html, body').animate({scrollTop:$(document).height()}, 'slow');
from 18252285, but it doesn't work. I get the following in the Chrome console:

Uncaught TypeError: Cannot read property 'scrollHeight' of null


You can setInterval the scroll, this will keep the page scrolled to the bottom

var simulateServerOutput = window.setInterval(function() {
  var $newElem = $('<div/>', {
    'html': Math.random().toString(36).substring(7)
}, 1000);

var autoScroll = window.setInterval(function() {
    var $target = $('html,body'); 
    $target.animate({scrollTop: $target.height()}, 1000);
}, 500);


This looks good, but how would I terminate this scroll loop? That is, after the page finishes loading, I don't want it to scroll to the bottom automatically. Is there some js I can append to the end, after all the linux commands finish, that will stop this? – synaptik 45 mins ago

to clear an interval (stop it) you can just execute clearInterval(autoScroll); But in you case how do you know when the page finished loading? you could use $(document).ready(function(){ ..... }); but this actually depends on the browser.

so a more complicated approach might be needed, such as taking a snapshot of the loaded content $('.content').html() this compare it every second to the latest snapshot and see if it is different. If it is not then that means it finished loading. then you can clear the timer.