unable to scroll to the bottom of a div after receiving new data through ajax requests

I'm having an issue with a div that has a scrollbar. Initially, the div scrolls to the bottom when loaded. However, after making a post request and loading new ajax data, it no longer scrolls to the bottom properly. It seems to be going to the "previous" bottom before adding the ajax data. Can anyone provide assistance with this?

<div id='messages'>
  <div id='message_box'>
    text messages
  </div>
</div>
// This script ensures that the page starts with the div scrolling to the bottom
$(document).ready(function() {
  var objDiv = document.getElementById("messages");
  objDiv.scrollTop = objDiv.scrollHeight;
})

// Although the ajax post request works, the scrolling to bottom in the success method is not functioning correctly
// It scrolls to the second last message instead of the last one, how can this be fixed?
var url_link = window.location.href;
$.ajax({
  data: {
    'text': 'text'
  },
  type: "POST",
  url: url_link,
  success: function() {

    $('#message_box').load(url_link + ' #message_box');
    var objDiv = document.getElementById("messages");
    objDiv.scrollTop = objDiv.scrollHeight;
  },
  error: function(e) {
    console.log("Bad request: " + e);
  }
#messages {
  overflow-y: scroll;
  width: 100px;
  height: 250px;
}

To summarize, the problem is that the message div does not scroll to the bottom of the div after the ajax post method. Instead, it stops at the second last message, requiring manual scrolling down to see the latest message. Any suggestions on how to resolve this would be greatly appreciated. Thank you.

Answer №1

It appears from the HTML structure that the load() function is inserting content into #message_box, affecting the height of #messages. To address this, make sure to update the scrollTop in the callback of the load() function, not the $.ajax() call. Here's a revised version:

let scrollToBottom = $container => $container.prop('scrollTop', $container.prop('scrollHeight'));

jQuery($ => {
  let $messages = $('#messages');
  scrollToBottom($messages); // automatically scroll down on page load
  
  let url_link = window.location.href;
  $.ajax({
    data: { text: 'text' },
    type: "POST",
    url: url_link,
    success: function() {
      $('#message_box').load(url_link + ' #message_box', () => scrollToBottom($messages));
    },
    error: function(e) {
      console.log("Error: " + e);
    }
  });
})

I made some adjustments to prevent redundancy and ensure the code executes after the DOM has finished loading.

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

To display a pattern with a series of alternating addition and subtraction operators, starting from -1 and ending at n, use JavaScript to iterate through the numbers and implement the pattern -1+

I've been struggling to locate the values despite numerous attempts. What steps can I take to resolve this issue? Below is my code snippet: var numVal = prompt(""); for (var i = 1; i <= numVal; i++) { if (i % 2 !== 0) { console.log("-"); ...

What is the best way to ensure all Promises are resolved in ExpressJS?

Context: I've developed a basic REST API in ExpressJS that enables the seamless integration of multiple web pages. The page numbers are flexible and can vary. Challenge: Due to constraints related to performance, I am keen on incorporating async pr ...

Passing and showcasing JSON information from one webpage to another upon clicking by utilizing local storage

I've been experimenting with a way to transfer JSON data from one page to another by using local storage. For instance, when a user clicks on a specific book image, they are directed to book.html where the image and book name are displayed (retrieved ...

Attempting to assign a class name to the <a> tag proves challenging as it seems to reset upon clicking the link, causing the class to vanish

Looking at this HTML code snippet <li> <a href="javascript:;"><i class="sidebar-item-icon ti-hummer"></i> <span class="nav-label">Product Management</span><i class="fa fa-angle-left arrow"></i>&l ...

The parameter type 'Function' cannot be assigned to the parameter type 'ComponentType<never>'

Having an issue passing a component to the connect method from react-redux. The error message I'm receiving is as follows: Argument of type 'Function' is not assignable to parameter of type 'ComponentType'. Type 'Function&ap ...

What is the best way to utilize JavaScript in order to eliminate a tag when an option is chosen within an HTML form?

I'm in the process of designing a website for an artist. The website includes a contact form, and I'm currently working on a JavaScript script to remove the hidden class that I applied to the commission rules section. The goal is to make this sec ...

Unable to view Mp4 video on Internet Explorer 11

My background video is in mp4 format and functions properly in Chrome, Firefox, and other browsers, but it does not work in Internet Explorer 11. To visit the website, click on "access as a non-secure site". ...

Is there a way to maintain the loop filters in archive.php when using AJAX?

I've been following a tutorial on using AJAX with jQuery and WordPress to add posts to my Packery.js layout. It's working perfectly on my home page, but I'm running into issues when trying to implement it on my archive pages. Instead of disp ...

What is the best way to determine the range in which the value falls?

Currently, I am working on validating whether a User has the required karma (reputation) to perform certain actions, such as placing a bid on an item. The karma value falls within the interval [-25; 100]. Additionally, it is noted that as a user accumulate ...

Different ways to make jQuery attr() method include the attribute by using single quotation marks

I start by creating a div in memory: var video_div = document.createElement('div'); video_div.className = "vidinfo-inline"; Next, I define some variables: var key = "data-video-srcs"; var value = '{"video1":"http://www.youtube.com/watch?v ...

React-Webcam: What is the solution for the error "Object may be null" and how to resolve "Type null is not compatible with type string or undefined"?

I'm encountering an issue with const imageSrc = webcamRef.current.getScreenshot(); Error: Object is potentially 'null'; and src={imgSrc} <img src={imgSrc} /> Error: Type 'null' cannot be assigned to type 'string | und ...

Text wrapping to the right of an image in Bootstrap columns

I'm struggling with getting a large block of text to display correctly on the right side of an image. The text keeps dropping below the image when it reaches a certain size or if no width is specified. Adding a fixed width to the text column seems to ...

PHP-generated HTML onclick attribute malfunctioning

Here is the PHP code I am currently working with: $listing .= "<button onclick='updateValue(".$id.", ".$key.")'>change value</button>"; The variable $id is an integer and functions correctly. However, $key is a reference from a for ...

The server is returning an unauthorized status when making a post request to the node, yet the client's fetch

While attempting to retrieve data through a fetch request on the front-end, I successfully obtained the type and id values as intended. export const getUserProfile = () => { return ( fetch( "https://api.spotify.com/v1/me", { headers: ...

Assistance needed in regards to relative positioning

I am working on a feature where the customer's shopping cart is displayed when they hover over "My Cart." I plan to achieve this effect using CSS, but I have encountered an issue with the size of .cart causing .my-cart to stretch... update The previ ...

Is it possible to fix the rightmost column in a scrollable HTML/CSS table with Angular when using overflow-x?

Is there a way to lock the right-most column in an HTML CSS Angular table that is scrollable using overflow-x? I have attempted using the sticky property and also creating two tables side by side, but neither method has successfully achieved the desired ...

"Utilizing jQuery's AJAX POST method with PHP is successful, while using XMLHttpRequest is not yielding

Currently in the process of revamping my existing code to transition from jQuery's AJAX function to using XMLHttpRequest in vanilla JS. My understanding is that the following code snippets should be equivalent. However, while the jQuery version functi ...

Prevent jQuery from triggering the infinite scroll until the next page has been fully loaded

In my custom WordPress template, I utilize this code snippet to achieve infinite scroll functionality. The button that triggers the AJAX request is placed at the bottom of the page for user convenience. Here's how I use it to automatically trigger the ...

What is the best way to update an element in an array inside a JavaScript object

In my NodeJS code, I have an object structured like this: const jsonData= { "description": "description", "hosts": [ "host1", "host2", "host3" ] } The task at ...

What is the process of combining JS functions with PHP echo in code?

I am currently working on creating a popout menu for an array of values that are being displayed from the database. The goal is to show the corresponding popout menu when the svg is clicked, but I am running into an issue where it only works for the first ...