If additional content has been included in the `div`, be sure to scroll all the way down to view it

I have a div that needs to automatically scroll to the bottom when new content is added. This is a common feature in chat applications where the user wants to see the latest messages without having to manually scroll down each time.

How can I achieve this functionality? I have tried the following code snippet, but it doesn't seem to be working as expected.

let tempCounter = 0;
var msgdiv = document.getElementById("messages");

function addContent() {
  msgdiv.innerHTML +=
    "Long long content " + tempCounter++ + "!<br/>";

msgdiv.scrollTop = msgdiv.scrollHeight;

}

setInterval(function() {
  addContent();

}, 500)
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.h-100 {
  height: 100%;
}

.flex-column {
  flex-direction: column;
}

.d-flex {
  display: flex;
}

.mh-100 {
  max-height: 100%;
}

.chat-messages {
  flex: 1;
  height: 100%;
  overflow: auto;
  display: flex;
  flex-direction: column-reverse;
}

.bg-white {
  background-color: #fff;
}

.chat-messages-text {
  display: flex;
  justify-content: flex-start;
}
<div class="d-flex flex-column h-100">
  <div class="chat-messages bg-white">
    <div class="chat-messages-text" id="messages">
    </div>
  </div>
  <div class="chat-input bg-warning ">
    <textarea class="form-control" id="inputs" rows="3"></textarea>
    <button type="button" onclick="addContent()" class="btn btn-primary mb-2"> Send Message </button>
  </div>
</div>

Answer №1

Implement the following code:

msgdiv.adjustScrollPosition(false);

This code snippet will ensure that the scroll view remains at the bottom of the element. (Switching 'false' to 'true' would keep it at the top.)

Answer №2

One way to track changes in your div element is by utilizing the Mutation Observer API. This allows you to automatically scroll to the bottom when a change is detected.

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

Adding Vuetify to a Vue web component, then proceed to pass props to enhance its functionality

Currently working on developing a web component with Vue and using vuetify component library. The goal is to export it as a web component, but facing difficulties when trying to pass props to the exported component in the index.html file. Following the ste ...

Rebel Spirit on a Wordpress Platform

I've encountered a strange issue on my Wordpress blog. For some reason, the code "&nbsp" is being inserted right after the opening <body> tag. I have checked the header.php file and there is no instance of this code present there. It's ...

Learn the process of adding transformation to an SVG path element

I have an SVG image loaded in my HTML file and I am trying to rotate one of its path elements, but I'm having trouble figuring out how to do it. The code snippet provided below is not working as expected. Can anyone provide guidance on how to achieve ...

Wait for Axios Request Interceptor to complete before sending another ajax call

One feature I have added is a request interceptor for all axios calls. This interceptor checks the JWT token and automatically refreshes it if necessary. axios.interceptors.request.use((config) =>{ const currentState = store.getState(); // get upd ...

When clicking on Submit, the code does not acknowledge the Verify Function

I am currently facing an issue with implementing the JQuery Ui function "Verify();" to ensure that the name, age, country, and date fields are completed before allowing form submission. Even though I have written the verify function to execute when the us ...

Discord.js: AbortError: The request was cancelled by the user

Recently, while working on my ticket system and the process for logging transcripts, I encountered an unexpected error that caused transcripts to fail sending. This issue never occurred before. The error message displayed was: [Error Handling System] Multi ...

Execute JavaScript code following the completion of loading and running an external script

My goal is to dynamically load and run a third-party JavaScript file (from a different domain) and then execute some of my own code afterwards. One option I'm considering is using jQuery's $.getScript: $.getScript('https://login.persona.org ...

What's the best way to vertically center text in a div with overflow hidden?

In my ASP GridView, I am trying to display a table with a fixed number of lines in each TD element. To achieve this, I have decided to place a div inside each TD so that I can customize the height and layout. table.XDataGridView td div.inner-table-div { h ...

How can I transfer a collection of JSON objects from JavaScript to C#?

Feeling a bit confused here. I have some Javascript code that will generate JSON data like the following: {type:"book" , author: "Lian", Publisher: "ABC"} {type:"Newspaper", author: "Noke"} This is just one example, I actually have more data than thi ...

Adjust the width of an element as its content dynamically shifts

I have a container that contains 6 input fields. Two of them are initially hidden (display: none), but when I click on a checkbox, these two inputs become visible (display: inline). I need the width of the container to adjust and increase when the other tw ...

The error message "Cannot construct apickli.Apickli" is indicating a Type Error

Encountering this issue : TypeError: apickli.Apickli is not a constructor every time I attempt to execute Sendpostrequest.js again in the following step of a scenario. In A.js, the initial call to Sendpostrequest works without any problems. However, ...

Tips for implementing a wait time for individual items in bee-queue

I've encountered an issue with the delayUntil function in the bee-queue library when creating a queue. await queue .createJob(process) .timeout(60 * 1000 * 2) .retries(2) .backoff('fixed', 60 * 1000) ...

Adjust background color on click using JavaScript

Could someone provide me with the JavaScript code to change the background color of a page from blue to green when a button is clicked? I have seen this feature on many websites but haven't been able to write the code myself. I am specifically lo ...

I envision my home page being divided into two visually stunning full-screen sections, each taking up the entire height of the page

I am currently working with the code shown below. It successfully displays the first part in full height, regardless of resolution, but once I scroll to the second half, there is a large empty gap. How can I eliminate this gap and make the transition smoot ...

Tips on customizing the appearance of React rendering components

<div> <h3>{this.props.product.name}</h3> <h3>{this.props.product.code}</h3> {this.renderColors()} <article> <div da ...

"Cookie Magic: Unleashing the Power of Ajax and

I am currently working on an ASP.NET 3.5sp1 application with a single page layout where all interactions are handled through ajax, eliminating the need for postbacks. The website in question is . This app does not require user accounts and allows anonymou ...

Cached images do not trigger the OnLoad event

Is there a way to monitor the load event of my images? Here's my current approach. export const Picture: FC<PictureProps> = ({ src, imgCls, picCls, lazy, alt: initialAlt, onLoad, onClick, style }) => { const alt = useMemo(() => initial ...

Error: Attempting to assign a value to the 'firstData' property of an object that is undefined

I am encountering two identical errors in my service. Below are the details of my service and controller: Service code snippet: getData: function (dataRecievedCallback, schemeid, userid) { //Average JSON api averageData = functi ...

Invoking a Components function from a Service in Angular may lead to a potential cyclic dependency issue

I am facing a challenge where I need to call a function from my filterComponent(component) within my engagementService(service). The function in my filterComponent accesses an array that is located within the engagementService. It uses the data from this ...

Firestore TimeStamp.fromDate is not based on UTC timing

Does anyone have a solution for persisting UTC Timestamps in Firestore? In my Angular application, when I convert today's date to a Timestamp using the code below, it stores as UTC+2 (due to summer time in Switzerland). import {firebase} from ' ...