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 div
, and fix the scrollbar to the bottom of this div
- 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 div
?
My cose so far is;
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js"></script>
<style type="text/css">
#result {
overflow: auto;
max-height:224px;
width: 500px;
}
</style>
<script type="text/javascript">
// scrollbar to bottom
$("document").ready(function(){
var objDiv = document.getElementById("result");
objDiv.scrollTop = objDiv.scrollHeight;
});
// retrieve data from server and display in div
$("document").ready(function(){
var source = new EventSource("data.php");
var offline;
$.ajax({
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
</script>
</head>
<body>
<div id="result"><!--Server response inserted here--></div>
</body>
</html>
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 div
.
I could be doing something very silly :)
Any advice is appreciated.