Ensure the scroll bar is positioned at the bottom without the need for setInterval() function

I am looking to ensure that the scroll bar remains at the bottom each time a user sends or receives a new message.

<script>
$ = jQuery;
var currentID = null;
var chatTimer = null;
var scrolled;

function fetch_data() {
  $.ajax({
    url: "select.php",
    method: "POST",
    success: function(data) {
      $('#live_data').html(data);
     }
  });
}

function fetch_chat() {

  $.ajax({
    url: "fetch_chat.php",
    method: "POST",
    data: {
      id: currentID
    },
    dataType: "text",
    success: function(data) {
      $("#chatbox").show();
      $('#messages').html(data);
      $("div.area").show();
      if(!scrolled){
      $('#messages').scrollTop($('#messages')[0].scrollHeight);
      scrolled=true;
      }
    }

  });

}

$(document).ready(function() {

 fetch_data();

  $(document).on('click', '.first_name', function() {
      scrolled=false;
    currentID = $(this).data("id1");
    fetch_chat();
});



  $("#sub").click(function() {

    var text = $("#text").val();
    $.post('insert_chat.php', {
      id: currentID,
      msg: text
    }, function(data) {
      $("#messages").append(data);
      $("#text").val('');
      scrolled=false;
      setInterval(function() {
    fetch_chat();}, 500);
    });
  });

});
</script>

My objective is to have the scroll bar automatically move to the bottom when a user sends or receives a new message, while still allowing manual scrolling according to the user's preference. I want the fetch_chat() function to be called periodically without affecting the position of the scroll bar - it should remain at the bottom initially, after new messages are sent or received, and be freely scrollable by the user.

Answer №1

Essential concept behind the solution provided:

The approach involves comparing the current chat HTML with the previous chat HTML. If they differ, then scrolling occurs; otherwise, no action is taken.

<script>
$ = jQuery;
var currentID = null,
    chatTimer = null,
    oldHtml = "";

function fetch_data() {
  $.ajax({
    url: "select.php",
    method: "POST",
    success: function(data) {
      $('#live_data').html(data);
     }
  });
}

function fetch_chat() {

  $.ajax({
    url: "fetch_chat.php",
    method: "POST",
    data: {
      id: currentID
    },
    dataType: "text",
    success: function(data) {
      $("#chatbox").show();
      $('#messages').html(data);
      $("div.area").show();
      if (oldHtml !== data) {
        $('#messages').scrollTop($('#messages')[0].scrollHeight);
      }
      oldHtml = data;
    }

  });

}

$(document).ready(function() {

 fetch_data();

  $(document).on('click', '.first_name', function() {
    currentID = $(this).data("id1");
    fetch_chat();
});



  $("#sub").click(function() {

    var text = $("#text").val();
    $.post('insert_chat.php', {
      id: currentID,
      msg: text
    }, function(data) {
      $("#messages").append(data);
      $("#text").val('');
      setInterval(fetch_chat, 500);
    });
  });

});
</script>

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

content localized with the help of a database

Is there a way to make my website multilingual without using an iframe translator? I want to change the entire page's content or other dynamically driven content to different languages based on user selection, rather than just parts of the text. Can y ...

The title is positioned at a different level compared to the ion-buttons in the toolbar

I am facing a challenge with the positioning of the logo in IOS compared to Android. On Android, the logo and buttons are aligned at the same height, but on IOS the logo appears higher than the buttons. Here is my code snippet: <ion-header> <i ...

Using jQuery to check if a value exists in a PHP array

I am encountering an issue with handling an array in PHP and using it in my jQuery code. Previously, I was able to successfully work with the array when it was a string, but now that it is more complex, the comparison of elements is not functioning properl ...

Validating Phone Numbers with jQuery - Only Accepting Prefixes of 3 Numbers Starting with (

I am new to using the jQuery validation method and I am trying to implement a check for a specific prefix. I have tried to do it myself but have been unsuccessful. Can anyone help me with this issue? Requirements:- Must start with 059 Example: 059XXXXXXX ...

Tips for adding a Search Bar to the header in a React Native application

I've been working on creating a header for my app in React Native that includes the screen title, a back button, and a search bar spanning the width of the screen. However, I've encountered some challenges along the way. Initially, I began with ...

Need help with calling a PHP file through AJAX and verifying the accuracy of my PHP code?

Having never worked with PHP before, I am uncertain if my code is correct. I am attempting to execute my PHP file from my JavaScript/jQuery code using ajax, but it doesn't seem to be functioning properly. No emails are getting sent, and there are no e ...

Cancel promise chain after action dispatch (rxjs)

My goal is to achieve the following: this.jobManager .queue( // initiate a job ) .then( // perform additional actions, but stop if `ABORT` action is dispatched before completion ) .finally( // carry out necessary ...

Using JQuery/JavaScript to Retrieve Boolean Values that have been modified locally

I'm struggling with booleans and scope in my code. I set a global boolean to false, which turns true upon a certain function call. The problem arises when I try to run another function based on this boolean - it remains false globally even after being ...

Change the icon switch from fas fa-lock-open to fas fa-lock by adding an event listener for a click action

let lockIcon = document.createElement("i"); lockIcon.setAttribute("class", "fas fa-lock-open"); lockIcon.setAttribute("id", color + "lock"); Is there a way to toggle between the icons fas fa-lock-open and fas fa-lock when clicking using a ...

Managing notification popup using JavaScript with Selenium WebDriver

Using Selenium WebDriver 2.53.1.1 in Visual Studio 2015 with C#. My testing application has Alert Pop Ups that I successfully handle using the code snippet below: ts.getDriver().SwitchTo().Alert().Accept(); Recently, I encountered a new challenge where ...

Having trouble accessing session value within an express router?

Within my app.js file: app.use(session({ secret: 'secureme123', key: 'hack123', cookie:{ maxAge:1000 * 60 * 60 * 24 * 30 }, store:new MongoStore({ db: 'hack123', host:'localhost', port: 27520, ...

Exploring the possibilities of incorporating Bootstrap 4 or ng-bootstrap elements into Angular 4 development

We are considering the use of Bootstrap 4 within an Angular 4 application by either importing their styles and JavaScript directly, or utilizing ng-bootstrap Angular components for improved performance and compatibility with the Angular app. We would lov ...

Hold down for File Menu to appear

Can a long press be used for triggering file dialog? I came across an interesting discussion about Long Press in JavaScript, where they discuss how to trigger an event on a long press. However, this method may not work for triggering file input click in ...

Assistance with CSS: How to Remove a Shape

Is it possible to remove the triangles above the element labels using CSS? To view them, click on a link (hear, see, savor). There is a dotted line and text with a small red triangle/arrow that is not centered. I have managed to disable them for the menus, ...

Issues with website display on LAMP server host causing viewing problems

As someone who is new to LAMP and web design in general, I appreciate your understanding as I navigate through any mistakes I may encounter. I have successfully set up a LAMP server on my Linux (Ubuntu) virtual machine and installed Wordpress. Everything ...

Increased spacing HTML

Trying to create a footer in HTML, but each time I attempt it ends up with an extra margin on the left side. Here is my current footer code: <div id="footer"> Tester </div> #footer { background-image: url(images/backgroundrpatternf ...

`A mistake occurred while building in the package.json file`

While attempting to run all build processes by using the command npm run build:css, I encountered an error indicated below. Even after running npm cache clean --force, the issue remains unresolved. https://i.sstatic.net/4edDo.png npm ERR! code ELIFECYCLE ...

The code isn't able to make use of the MongoDB FIND method

When I attempt to search for items in a collection using the console with db.DB_NAME.find({ x: y }, it works perfectly. However, when trying to do the same in the code, it doesn't seem to work. It's worth mentioning that the findOne method works ...

Searching for an equivalent to AdRotator within the .NET framework

Currently, I am developing a website that features rotating testimonials. I am interested in finding a solution similar to the AdRotator class available in .NET. However, instead of rotating images, I need a method to rotate formatted text blocks using HTM ...

Using Python and BeautifulSoup to extract the values of a tags nested within multiple other tags

<a href="link" target="_blank" class="xXx text-user topic-author" sl-processed="1"> diamonds </a> My task is to extract the word 'diamonds' from the 'a' tag using BeautifulSoup. Although I have attempted various method ...