0

I know numerous questions have been asked about this, but I've not seen one that is the same as my requirement.

I have a div and data is added to it by calling an external page and then writing the results live to the div. That works fine using:

<div id='test'>

$x = popen("php test.php", 'r');

while($y = fgets($x, 512)) {
    echo "$y<br>";
    ob_flush();flush();
}
pclose($x);

</div>

test.php is echo'ing its results and the div is updated.

I need to keep test div scrolled to the bottom. I've been doing it by adding a new line after the echo $y like so:

echo "<script>var objDiv = document.getElementById(\"test\");objDiv.scrollTop = objDiv.scrollHeight;</script>";

But I feel there is a better way to do that then keep echoing that script.

Can anyone advise how to keep the div scrolled to the bottom ?

Is there no way to bind an event that detects content change on the div and then scrolls to the bottom, without having to echo the same code over and over ?

Thanks

The ticket referenced as a duplicate is discussing scrolling to the bottom of the div, NOT how to scroll to the bottom of the div as it it being updated.

Tom
  • 1,436
  • 24
  • 50

1 Answers1

0

You can use jQuery bind-Event:

$('.box').bind("DOMSubtreeModified propertychange", function(e) {
    $(this).animate({ scrollTop: $(this).prop("scrollHeight") }, 100);
});

working fiddle

if you retrieve the data over ajax $(document).on()

$(document).on("DOMSubtreeModified propertychange", ".box", function(e) {
        $(this).animate({ scrollTop: $(this).prop("scrollHeight") }, 100);
});

working fiddle

Source: Jquery Event : Detect changes to the html/text of a div

DOMSubtreeModified is not working on IE.

Edit: Added `propertychange for IE-support.

Community
  • 1
  • 1
Slatyoo
  • 130
  • 15
  • thanks for this is there a way to do this across browsers ? – Tom Feb 13 '17 at 09:26
  • edited answer. this should work in ie (cant test it right now) – Slatyoo Feb 13 '17 at 09:35
  • Thanks - Just tried this in Chrome and it didn't work. Data is added to the div but it doesn't scroll to the bottom. – Tom Feb 13 '17 at 10:03
  • are you retrieving your data over an ajax-request? if so use `$(document).on("DOMSubtreeModified propertychange", ".box", function(){});` – Slatyoo Feb 13 '17 at 10:05