Search code examples
phpjavascriptscrollflush

php ob_flush : How do I make the browser window/page scroll down with the output?


Searched a fair bit but couldn't find much about this..

I have a page that is processing quite a few things through a loop, and I have put this at the top of the php page:

ob_implicit_flush(true);
ob_end_flush();

This is happily pumping out the loop to my browser window, but the content is scrolling off the bottom of the page, and I have to keep scrolling down manually. So my question is: How do I get the page or browser window to scroll with the content?

I read somewhere using javascript setInterval to start and end scrolling might do the trick, and it sounds like that might be the case - just make the page start scrolling at the beginning of the script and end when it ends.. but I'm not great with javascript yet so was hoping someone could tell me how to do it?

Another solution I can think of is to somehow get javascript to force focus on a particular element class or something as it is being generated.. but this seems like a potentially clunkier option..

Any quick tips would be great.

Thanks!


Solution

  • There is no need to add thousands of lines of code, just a short function at the top of your output and a line at the end. This works (add the html at the beginning and /html at the end tags to make it pretty; no need though):

    <script>
    var scroller = setInterval(function() {  
        window.scrollTo(0,document.body.scrollHeight);
    }, 10); // update every 10 ms, change at will
    </script>
    <?php
    // generate 1000 lines of html code
    for($i=0; $i<1000; $i++){
        echo $i . "<br>";
        ob_flush(); // flush out the output as we go
        flush(); // same
        usleep(10000); // add some delay to see it in action  
    }
    
    ?>
    
    <script>
    clearInterval(scroller); // stop updating so that you can scroll up 
    </script>