TheOrdinaryGeek TheOrdinaryGeek -3 years ago 104
Ajax Question

Live Data Feed and Scrollbar Position

I am retrieving data from a MySQL database and displaying it on a website using the EventSource API. So far everything is working as expected, but I want to display the data in a fixed height

, and fix the scrollbar to the bottom of this
- i.e always show the latest feed results first.

Now when I load the page the scrollbar is fixed to the top.

I have tried the suggestion here but it doesn't seem work. Is it because I am working with live data and AJAX requests in order to populate the

My cose so far is;

<!DOCTYPE html>
<html lang="en">
<script src=""></script>
<style type="text/css">
#result {
overflow: auto;
width: 500px;
<script type="text/javascript">
// scrollbar to bottom
var objDiv = document.getElementById("result");
objDiv.scrollTop = objDiv.scrollHeight;
// retrieve data from server and display in div
var source = new EventSource("data.php");
var offline;
type: "POST",
url: 'data.php',
data: {lastSerial: true},
dataType: 'json',
success: function(data){
$.each(data, function(key, value) {
document.getElementById("result").innerHTML += "New transaction: " + value.SerialNo + ' ' + value.TimeStamp + "<br>";
} // end success
});//end dom ready
<div id="result"><!--Server response inserted here--></div>

The strange this is, whenever I remove the live feed javascript and manually add some (lorem ipsum) text into the
<div id="result">
it works, the scrollbar appears at the bottom of the

I could be doing something very silly :)

Any advice is appreciated.

Answer Source

When you load more data via ajax, the size of the content will change. Have you tried setting the scroll again after you've rendered the content? i.e.:

  success: function(data){
      var objDiv = document.getElementById("result");

      $.each(data, function(key, value) {
          objDiv.innerHTML += "New transaction: " + value.SerialNo + ' ' + value.TimeStamp + "<br>";
      objDiv.scrollTop = objDiv.scrollHeight;
     } // end success

Thus setting the scroll value the same way you do when the page loads.

Alternatively, here's another completely different option:

If you want the most recent values to be most prominent, you could simply output them in reverse order, so the newest ones are at the top of the div, where the user will see them first. You can use jQuery's .prepend() method to add content to the beginning of the div, above the previous results. Then there's no need for messing about with scrolling. I'd argue this is more user-friendly, but it's up to you obviously.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download