The content within the div appears to be in a perpetual state

I'm working on creating a chat application with a single interface. I've encountered an issue where the content in the middle div "messages" keeps bouncing, including the scroll bar. How can I resolve this problem?

Additionally, I'm unable to keep the scroll bar at the top position. Any tips on fixing this as well?

Below is my complete code:

Main code :

<?php
            include 'db.php';
            if(isset($_POST['send']))
            {
                header("Location:chat.php");
                $chat=$_POST['chat'];
                $sql="INSERT INTO chat_info(chat) values('$chat')";
                $query=mysqli_query($conn,$sql);

            }
        ?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat Application</title>
    <style>
        /* Your CSS styles here */
    </style>
</head>

<body>
    <!-- Your HTML content goes here -->
</body>

 

Additional PHP function for connecting to the database :

<?php
$host="localhost";
$user="root";
$db="chat";
$conn=mysqli_connect($host,$user,"",$db);
if(! function_exists('formatDate'))
{
    function formatDate($date){
    return date('g:i a',strtotime($date));
}
}
?>

Answer №1

The problem lies in the constant addition of new messages even when there are none to add. This specific line of code setInterval(getMessages, 100); is responsible for adding a new message every 0.1 second, causing the page to automatically scroll to the bottom each time, making it impossible to scroll back to the top.

To resolve this issue, consider either adjusting the interval timing or incorporating a check for empty messages like the following:

if (newMessage.textContent !== ""){
    messages.appendChild(newMessage);
}

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

What causes the child positioning to break when a CSS-Filter is applied to the parent element?

One of my projects includes a title-screen "animation" where the title is initially centered on a fullscreen page and then shrinks and sticks to the top as you scroll down. I have provided a simplified working example below: $(window).scroll( () => ...

Issue encountered while trying to interpret Bootstrap 4 within Netbeans 8.2

Currently, I am working on an HTML5/JS application using Node.js in Netbeans 8.2. As I develop the welcome page, I intend to incorporate Bootstrap 4. However, when I attempt to add bootstrap.min.css to my stylesheets folder, I encounter an error as shown i ...

Displaying a JSON array based on certain criteria using ng-repeat

Hey there, I've got a JSON array that looks like this: var homes = [ { "city": "Dallas", "state": "TX", "zip": "75201", "NoteNumber": "162500" }, { "city": "Bevery Hills", "state": "CA", ...

What is the most effective way to eliminate asynchronicity in a function?

Imagine having this block of code: const myFunction = async => { const result = await foobar() } const foobar = async () => { const result = {} result.foo = await foo() result.bar = await bar() return result } Now, let's transform i ...

What is the best method for me to filter the values in my array?

I need to add a value to an array based on certain conditions. My code looks something like this: var newEmployee = []; $scope.employees = [{'id':1, 'new':true},{'id':2, 'new':false}{'id':3, 'new&apo ...

Is history.pushState capable of more than just making an xhr request?

I've hit a roadblock in my current project. The issue I'm facing is getting a registration page to load. The XHR request is returning the output of the PHP code, which is causing problems. My goal is to have it load as a document rather than an ...

What is the best way to incorporate CDN into my webpack build process?

I have developed a module with the following code: export default () => console.log('hello my_module~!') The configuration in the webpack.config.js file looks like this: module.exports = { // ... output: { // ... library: 'he ...

What is the best way to disengage a loop of elements within an internship?

In my scenario, the DOM structure is as follows: <table id="campaigns"> <tr> <th>Name</th> <th>Status</th> </tr> <tr> <td>first data</td> </tr> <tr data- ...

When clicked, check if the CSS value is equal to

I have no idea why it's not working. After toggleClass is executed, if the CSS value equals "-84%" then hide(); $(".rwd-sec").click(function() { $(".rwd-main").toggleClass("is-active"); if ($(".rwd-main").css("right") == "-84%") { ...

Connecting Mailchimp with WordPress without using a plugin can lead to a Bad Request 400 error when trying to

I'm attempting to connect with Mailchimp using an Ajax request without relying on a plugin, but I keep encountering a 400 bad request error. The code provided below utilizes vanilla JS for Ajax and the function required for integration with Mailchimp. ...

Executing Javascript code from a specified web address

Let's say I have an image that needs to be shifted vertically, and I achieve it using the following code snippet: document.getElementById('ImgID1').style.verticalAlign = However, the value by which I need to shift the image is provided thr ...

Tips for adjusting the position of the second child in my navigation menu using CSS

Struggling with customizing my navigation menu in CSS, I'm seeking assistance. My goal is to have the second child element of the navigation menu on a new line instead of below the first child (refer to the image for clarification). An example of the ...

What is the correct method for adding a button to a popup in Leaflet Draw?

I need a button within a popup that can perform an action on the attached layer. L.marker(coors[i], { icon }) .addTo(this.drawnItem) .bindPopup(this._getCustomIcon(mix)) .openPopup(); Here is my _getCustomIcon() function: ...

Unable to locate phonepe.intentsdk.android.release:IntentSDK:2.4.1 while integrating React Native

android build gradle : // Configuration options for all sub-projects/modules are defined in the top-level build file. buildscript { ext { buildToolsVersion = "33.0.0" minSdkVersion = 21 compileSdkVersion = 33 targetSdkVersion = ...

Utilizing htmx for interactive elements throughout the website

When I make an htmx-request on my page, a loading spinner is displayed like this: <div class="col-4 px-4dot5 py-3 bg-secondary-light"> <label for="stellenangebotLink" class="form-label fs-5">Link</label> ...

Is there a way to position the logo icons on the right side of the footer?

My goal is to connect social media platforms with their respective logos, and I'm encountering an issue. The problem arises when attempting to align the list items to the right of the footer. <footer> <div class="footer-wrapper"> ...

Tips for integrating SASS from the Bulma package into an Angular application

I'm currently working on implementing Bulma into my project. The documentation suggests using NPM to obtain it. yarn add bulma Further in the documentation, there is an example provided with code snippets like the ones below. <link rel="styles ...

Click on every link to reveal a hidden div

When I click on and select the first link in the mainPart, I want to automatically select the first subLink div in the secondPart while hiding the other subLink classes. This sequence should be maintained: when the second link is selected, the second sub ...

When executing tests in jest, imports from node_modules may become undefined

My jest configuration seems to be encountering an issue with resolving node_modules during execution. They are coming back as undefined... Here is a snippet from my test file: import lodash from 'lodash' it('test', () => { expect ...

Remove bulleted list from HTML using JavaScript DOM

My task involved deleting the entire "agent" array using the removeChild() function, requiring the id of a <ul> element. However, I faced an issue as I couldn't set the id for the "ul" due to using the createElement() function. //old code < ...