Chat Room with Stable Div Size

I am working on developing a chat feature, but I am facing an issue where the new message does not appear on the screen after a certain number of messages. I want the messages to overflow so that users can scroll down to view them, but only a few messages are displayed and nothing happens after that point. The previous messages remain static on the screen. I am using React along with Socket.io for this project. Here is the code snippet:

const [messagesAndAuthors, setMessagesAndAuthors] = useState<any>([]);

useEffect(() => {
            socket.on('receivedMessage', (newMessage:{}) => {
                messagesAndAuthors([...messagesAndAuthors, newMessage])
            });
    })
    
function sendingMessages(e : FormEvent) {
        e.preventDefault();
        if(message.trim()) {
            const messageObject = {
                userName,
                message,
                roomId
            };

            socket.emit('sendMessage', messageObject);
        }

        setMessage('');

    }
    
----------------------------BACK-END(SOCKET.IO):

socketInfo.on('sendMessage', (data:any) => {
        socketInfo.broadcast.emit('receivedMessage', data);
    });
.chat-container {
    margin: 0.5rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    font: 400 1rem 'Sulphur Point';
    background-color: #254441;
    padding: 2rem 0;
    border-radius: 2rem;
    justify-content: space-between;
    text-align: center;
    max-height: 77.5vh;
    overflow: auto;
}

.chat-container h1 {
    background-color: #ff6f59;
    padding: 0.2rem 4rem;
    border-radius: 2rem;
    text-align: center;
    align-items: center;
    justify-content: center;
    margin-bottom: 1rem;
}

.messages-container {
    text-align: start;
    background-color: #254441;
    border-radius: 2rem;
    height: 90%;
    margin-bottom: 0.5rem;
    overflow: auto;
}

.messages-mine-style {
    width: 15rem;
    border: transparent;
    border-radius: 1.5rem;
    margin-top: 2rem;
    text-decoration: none;
    text-align: start;
    list-style: none;
    font: 700 1.4rem 'Sulphur Point';
    padding: 0.2rem 0.6rem;
    margin: 1rem 0;
}

.messages-mine-style li{
    margin-left: 1rem;
}

.messages-mine-style li+li {
    font: 400 1.4rem 'Sulphur Point';
}

.chat-container input {
    background-color: #ff6f59;
    padding: 1rem 4rem;
    border-radius: 2rem;
    text-align: center;
    font: 700 1.2rem 'Sulphur Point';
    outline: none;
    border: transparent;
}

.chat-container input::placeholder {
    color: #254441;
}
<form onSubmit={sendingMessages} className="chat-container">
                        <h1>Chat</h1>
                        <div className="messages-container">
                        {messagesAndAuthors.map((messageWithTheAuthor:any) => {
                                 return (
                                    <>
                                    <ul className="messages-mine-style">
                                        <li key={messageWithTheAuthor.author}>{messageWithTheAuthor.author}: </li>
                                        <li>{messageWithTheAuthor.message}</li>
                                    </ul> 
                                    </>
                                )        
                        })}
                        </div>                                                                      
                        <input value={message} onChange={(e) => {setMessage(e.target.value)}} type="text" placeholder="Type your message here"/>        
</form>

Answer №1

Here's a sample illustration. It may require customization to suit your needs, but it can provide a solid foundation for you to build upon.

function adjustScroll() {
  let element = document.getElementsByClassName("chat")[0];
  let difference = element.scrollHeight - element.scrollTop;
  if (difference < 120) element.scrollTop = element.scrollHeight;
}

var messageCount = 1;

function updateMessages() {
  let Message = "<li class=\"chat-message\">new message "+ messageCount++ +"</li>";
  document.getElementsByClassName("chat-messages")[0].innerHTML += (Message);
  adjustScroll();
}

setInterval(updateMessages, 2000);
updateMessages();
.chat {
  width: 250px;
  height: 100px;
  overflow: auto;
  background-color: darkgray;
  border: solid black 1px;
  border-radius: 2px;
}

.chat-message {
  list-style-type: none;
}

.chat-messages {
padding: 0px;
padding-left: 5px;
margin: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="chat">
  <ul class="chat-messages">
  </ul>
</div>

This instance will solely scroll down when the user has reached the bottom. If the user scrolls up (to view past messages), the scrolling feature will not activate automatically.

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

Ways to adjust the ngx-pagination color scheme?

I am looking to customize the background color of ngx-pagination Here is my current code: <pagination-controls class="custom-pagination" id="indicadorPaginationResults" (pageChange)="p=$event" maxSize="9" directionLinks="true" autoHide="true" previ ...

how can JavaScript be used to retrieve an object based on a condition from an array of objects and an ArrayList

My JavaScript challenge involves working with an array of objects called arrobj and a list called prgList. The goal is to extract the names from arrobj based on the programs listed in prgList. If the program exists in arrobj, it should be displayed accor ...

Display HTML code inside a specified div

I am attempting to incorporate content from another HTML file into my current web page using jQuery's .load method. Unfortunately, the content is not loading as expected. Can anyone provide me with a solution to this issue? Below is the HTML and jQ ...

A guide on displaying containers with jQuery and CSS

Looking to create a smiley survey using only Front-End technologies. Once a radio button is selected, the associated content should appear for comments. Currently, I have set up my CSS with display: none. I attempted to implement this functionality using ...

Refreshing ApolloClient headers following a successful Firebase authentication

I am encountering an issue while trying to send an authorization header with a graphql request when a user signs up using my React app. Here is the flow: User signs up with Firebase, and the React app receives an id token. User is then redirected to ...

Argument-based recursive method

Why is the script only printing 'Hello' and not 'Good bye' as well, even though both are passed as arguments on the function call? What could be causing this issue? Note: The script used to work before. It stopped working after adding ...

Using local storage with github sites can lead to some unexpected and peculiar behavior

Currently, I am working on a simple clicker game using HTML and JavaScript. To store the variables money and taxCollecters, I have implemented local storage. However, I am encountering strange issues when trying to use the save and load buttons on the Gi ...

The images are not properly aligned with the carousel in Bootstrap 4

I am having an issue with my carousel displaying zoomed-in images. Here is the HTML code I am using: <header> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> ...

Storing non-serializable objects globally in React Native: Best practices and solutions

This is a React Native project. Requirement: In my project, I am looking to initialize a 3rd party client only once The client object cannot be serialized I need to be able to access the object across different components Essentially, I require somet ...

Validation of React Input for empty values or numbers

Looking for assistance with improving my method for checking the state of the calculator input and determining if it is empty or not. Here are the two issues I need help with: Is there a more elegant solution to incorporate a validation check to ensure ...

The type '{}' is lacking the 'submitAction' property, which is necessary according to its type requirements

I'm currently diving into the world of redux forms and typescript, but I've encountered an intriguing error that's been challenging for me to resolve. The specific error message reads as follows: Property 'submitAction' is missing ...

The custom shader material and texture in Three.js are not blending seamlessly with the rest of the scene

https://i.sstatic.net/yNxD5.gif Within my Three.js environment, I am encountering an issue where my texture fails to blend with other textures at certain viewing angles, while all other elements continue to function properly. Any suggestions on how to res ...

Incorporate an email sign-up form at the conclusion of the video

I have a challenge of implementing an email sign up form that should be triggered when a video ends. I have managed to display an alert message upon the video ending, but I am unsure how to integrate the form using JavaScript. Can anyone provide some guida ...

Unable to invoke the AppComponent function within ngOnInit due to error message: "Object does not have the specified property or method"

I'm a novice in Angular and I am attempting to invoke my function setCenter2() from the AppComponent class within the ngOnInit function of the same class. Is this achievable? Whenever I try to call my function by clicking on the map (using OpenStreetM ...

What steps can be taken to resolve the error message "Warning: useLayoutEffect does not have any effect on the server"?

Here is the error message I keep encountering: Warning: useLayoutEffect does nothing on the server, because its effect cannot be encoded into the server renderer's output format. This will lead to a mismatch between the initial, non-hydrated UI and ...

Is there a correct way to properly duplicate a JSON array in Redux?

As a newcomer to Redux, I found the concepts somewhat confusing at first. For instance, imagine that there is an array in the redux state. const state = [ {show: false, id : '1'}, {show: false, id : '2'}, {show: false, id : &apo ...

Issues arise when attempting to set a cookie in ReactJS with .NET

I am facing an issue with setting an HTTPOnly Cookie in my .NET5 API controller. Despite using the code Response.Cookies.Append("refreshToken", token, cookieOptions), the cookie is not showing up in Chrome's "Application" tab when I try to access it f ...

Dynamically changing the date format within the item-text of v-autocomplete in Vuetify

My current v-autocomplete component is fetching an array of items from GrowthTasks.edges to display. <v-autocomplete label="Start Week" :items="GrowthTasks.edges" item-text="node.growthStartDate" item-value="node.grow ...

Struggling to implement custom media queries in a bootstrap theme

I've customized the Twitter Bootstrap layout for my website, and everything is looking great except for the @media queries. Can anyone help me figure out what's going wrong? HTML: <section id="lessons" class="bg-black no-padding lesson-conte ...

Validating a single field for City, State, and ZIP in jQuery/JavaScript

I am trying to validate an input field that requires City, State (two letter abbreviation), and ZIP code (5 numeric digits) in the format 'City, State ZIP'. Could someone please help me with validating this specific format and characters? Appre ...