Utilizing the EventSource API, I am pulling data from a MySQL database and showcasing it on a website. Everything is running smoothly as planned, but my goal is to exhibit the data in a fixed height div
, with the scrollbar constantly positioned at the bottom of this div
- ensuring that the most recent feed results are always displayed first.
Upon initial page load, the scrollbar remains fixed at the top.
I attempted the solution suggested here, however, it does not seem to be effective. Could this issue be due to working with live data and AJAX requests to populate the div
?
Here is what I have done so far;
<!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 peculiar aspect is that when I eliminate the live feed javascript and manually add some placeholder text (lorem ipsum) into the <div id="result">
, the scrollbar functions correctly by displaying at the bottom of the div
.
It's possible that I'm overlooking something simple :)
Any advice would be greatly appreciated.