Real-time Data Stream and Navigation Bar Location

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.

Answer №1

When you fetch additional data using ajax, the size of the content will change. Have you attempted to reset the scroll position after the content has been loaded? For example:

  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
 });

This way, the scroll position is set in the same manner as when the page initially loads.


On a different note, here's an alternative approach:

If you prefer to highlight the most recent values, you can display them in reverse order, with the newest ones appearing at the top of the div for immediate visibility to the user. You can achieve this by using jQuery's .prepend() method to insert content at the beginning of the div, above the existing results. This eliminates the need to adjust the scrolling behavior. http://api.jquery.com/prepend/ It could enhance the user experience, but ultimately, the choice is yours.

Answer №2

It seems that there might be an issue with the way you are handling the asynchronous AJAX call in relation to scrolling to the bottom of the div.

You could possibly consider adjusting your approach to something like this:

<!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">
        $("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>";
                        });
                    var objDiv = document.getElementById("result");
                    objDiv.scrollTop = objDiv.scrollHeight;
                 }
             });
         });
    </script>
</head>
<body>
    <div id="result"><!--Server response inserted here--></div>
</body>
</html>

Explanation: In this adjusted setup, the population of the div occurs before executing the scroll action, which should ensure that the scrollHeight property reflects the updated height of the div. This sequence may help resolve any issues encountered when scrolling to the bottom of the div after performing the asynchronous AJAX call.

Answer №3

const targetDiv = document.getElementById("result");
targetDiv.scrollTop = targetDiv.scrollHeight;

This script is not anchoring the scrollbar to the bottom but is instructing it to scroll down by the height of the div once. Since this code is positioned before your ajax request, ensure that your div is empty when executed. To resolve this, simply move these two lines to the end of your ajax "success" function.

success: function(data){
    $.each(data, function(key, value) {
        document.getElementById("result").innerHTML += "New transaction: " + value.SerialNo + ' ' + value.TimeStamp + "<br>";
    });
    const targetDiv = document.getElementById("result");
    targetDiv.scrollTop = targetDiv.scrollHeight;
}

Answer №4

There was just a tiny mistake in your code snippet, make sure to include the following line:

 $.ajax({
  type: "POST",
  url: 'data.php',
  data: {lastSerial: true},
  dataType: 'json',
  success: function(data){
      var objDiv = document.getElementById("result");

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the wonders of Angular 2: Leveraging NgbModal for transclusion within

If I have a modal template structured like this: <div class="modal-header"> <h3 [innerHtml]="header"></h3> </div> <div class="modal-body"> <ng-content></ng-content> </div> <div class="modal-footer"& ...

Incorrect measurement of text size

My attempt at creating a basic font size changer was working perfectly until I integrated it with the bootstrap framework. Strangely, when I try to increase the font size, it actually decreases instead. var baseFontSize; (function () { "use strict"; ...

Searching for the precise error name being thrown in MySQL using Node.js

Currently, I am in the process of constructing a server using node.js (express) and mysql felix. The issue I am facing is that occasionally I encounter a duplicate error when running a certain query. I have exhausted all of my attempts to handle this err ...

Is there a method to exempt a particular input field from form validation?

Is there a way to prevent a form validation error message from displaying in other input fields when using an input url field within a rich text editor component (RTE) placed inside a form element? <input type="url" v-model="state.url ...

Why does the Next.js GET index request keep fetching multiple times instead of just once?

Currently, I am encountering an issue while working on a tutorial app with Next.js. One of my components is not rendering due to what seems like multiple executions of a simple GET request for an index page. The problem perplexes me, and I need some assist ...

Creating an Ajax search feature using Symfony and Jquery

Hey everyone, currently I am working on a Symfony project and I'm trying to implement a real-time search using AJAX. However, I've encountered an issue where the search is returning all data from the database instead of filtering based on my keyu ...

What is the process for setting data to the value attribute in an input tag, retrieved from a firebase database?

I utilized the following code snippet to retrieve data from Firebase database and store it in the Name variable. var userId = localStorage.getItem('keyName'); var dbRefName = firebase.database().ref() .child(& ...

What is the best way to make sure the background color of a container stretches across the full width of the screen?

I am currently learning HTML and CSS, and as a practice project, I am working on building a portfolio webpage. In the image provided, there are two containers, and I am facing an issue with the space on the sides when changing the background color. Despite ...

Guidelines for transferring data from a controller to jQuery within a CodeIgniter view

Currently, I am immersing myself in web programming through framework codeIgniter. My aim is to pass a value from a function within the controller to the query script located in the view file. Here's the snippet of code inside my controller: public f ...

Using React-router-dom's Link component can cause styling inconsistencies with material-ui's AppBar Button

Exploring the use of a material-ui Button with react-router-dom's Link is showcased here: import { Link } from 'react-router-dom' import Button from '@material-ui/core/Button'; <Button component={Link} to="/open-collective"> ...

How can elements be displayed differently depending on the return value of a function?

Basically, I am looking to display different content based on the status of a job: Show 'Something1' when the job is not processing Show 'Something2' when the job is running and has a status of '0' Show 'Something3&apos ...

A sleek Javascript gallery similar to fancybox

I'm currently working on creating my own custom image gallery, inspired by fancybox. To view the progress so far, please visit: I've encountered some issues with the fade effects of #gallery. Sometimes the background (#gallery) fades out before ...

Error: Unable to iterate over the elements of `this.state` as it is

NEW UPDATE I encountered an issue with the response being an array, but it was actually coming from the backend (Express/Build folder) Revisiting an old issue that I faced some time ago. In my development environment, everything works fine. But once I d ...

Ionic - numerical age selector control

Currently working on a hybrid mobile app and ran into a specific issue. I'm in the process of adding new items to my left side menu, including an age number spinner component (min:18, max:65). After searching through various sources and Ionic documen ...

What is the best way to extract the HTML input id using observeEvent in shiny?

How can I capture the HTML input id using observeEvent in shiny? shinyApp( ui = basicPage( HTML('<input type="button" name = "b1" value="Travel time"/>')), server = function(input, output, session) { o ...

When my script is located in the head of the HTML page, I am unable to

My goal is to make my JavaScript code function properly when I insert it into either the head or body elements of an HTML document. Let's look at some examples: First, I insert the script into the body as shown in this example (works correctly): ...

The React functional component fails to update when triggered by a parent component's setState method

My React component is utilizing apollo to fetch data through graphql class PopUpForm extends React.Component { constructor () { super() this.state = { shoptitle: "UpdateMe", popupbodyDesc: "UpdateMe" } } re ...

Convert angular-tree-component JSON into a suitable format and dynamically generate checkboxes or radio buttons

Currently, I am using the angular-tree-component for my treeview implementation. You can find more details about it in this reference link. The array structure I am working with is as follows: nodes = [ { id: 1, name: 'root1', ...

When calling a method that has been created within a loop, it will always execute the last method of the

In my project, I am utilizing node version 0.8.8 in conjunction with express version 3.0. Within the codebase, there exists an object named checks, which contains various methods. Additionally, there is an empty object called middleware that needs to be p ...

ReactJS & MobX: Unusual TypeError Occurs - Functionality Issue?

This code snippet defines the SidenavStore.js, which determines if the Sidenav should be visible or not by default: const SidenavStore = types .model('SidenavStore', { isSidenavVisible: types.optional(types.boolean, true), }) .actions( ...