The chat text will automatically scroll down, displaying information loaded from the database

Is there a way to ensure that chat text always remains scrolled to the bottom of the chat?

I have tried multiple tutorials and examples from Stack Overflow, but none seem to work for me.

Currently, my chat text overflows the textarea when there are too many lines, despite having overflow:hidden set.

I also want the textarea to only load the last 50 entries from the database so that new users don't have to load all previous chat messages.

Any suggestions on how to achieve these two things?

home

<?php
    session_start();
?>

<!DOCTYPE html>
<html>
<head>
    <div id="Holder">
        <div id="Header"></div>
   <link href="../Style/Style.css" type="text/css" rel="stylesheet"/>

    <script type="text/javascript" src="../Js/jquery.js"></script>
    <title>Chat Home</title>
    <script type="text/javascript">
        $(document).ready(function(){

            $("#ChatText").keyup(function(e){
                //When we press Enter do
                if(e.keyCode==13){
                   var ChatText =  $("#ChatText").val();
                    $.ajax({
                        type:'POST',
                        url:'InsertMessage.php',
                        data:{ChatText:ChatText},
                        success:function(){
                            $("#ChatMessages").load("DisplayMessages.php");
                            $("#ChatText").val("");
                        }
                    })
                }
            });
            setInterval(function(){//refreshes every 1500ms
                $("#ChatMessages").load("DisplayMessages.php");
            },1500);
            $("#ChatMessages").load("DisplayMessages.php");

    </script>
</head>
<body>
<h2>Welcome <span style="color: green"><?php echo $_SESSION['UserName'] ; ?></span> </h2>
</br></br>

<div id="ChatBig">
    <div id="ChatMessages">
    </div>
    <input type="text" id="ChatText" name="ChatText"></textarea>
</div>
<div id="Footer"></div>
</div>
</body>

</html>

Css

#ChatBig {
    width: 60%;
    height: 600px;
    margin: auto;
    background-color: white;
    overflow:hidden;
    resize:none;

}
#ChatMessages{
    width: 100%;
    height: 548px;
    border: 1px solid #000;
    font-size: 16px;
    font-weight: normal;
    overflow:hidden;
    resize:none;
}
#ChatText{
    width: 100%;
    height: 50px;
    border: 1px solid #000;
    overflow:hidden;
    resize:none;
}
#ChatText:focus{outline: none;}

body {
    background-color: lightgray;
}
#Holder {
    width: 100%;
}
.UserNameS{
    color: #7CB9E8;
}
.UserNameS:hover{text-decoration:underline; cursor: pointer;}

Image of how the site looks

http://gyazo.com/fe71d7d9699b9784fda5ba1c862fad53

Answer №1

If you prefer not to have scrolling, you can consider using position: absolute; and position: relative;. Here's an example:

#ChatBig {
    width: 60%;
    height: 600px;
    margin: auto;
    background-color: white;
    overflow:hidden;
    resize:none;
    background: red;
    position: relative;
}
#ChatMessages{
    width: 100%;
    min-height: 498px;
    border: 1px solid #000;
    font-size: 16px;
    font-weight: normal;
    overflow:hidden;
    resize:none;
    position: absolute;
    bottom: 50px;
}
#ChatText{
    width: 100%;
    height: 50px;
    border: 1px solid #000;
    overflow:hidden;
    resize:none;
    position: absolute;
    bottom: 0;
}
#ChatText:focus{outline: none;}
<div id="ChatBig">
    <div id="ChatMessages">
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        asd<br/>
        qwe<br/>
    </div>
    <input type="text" id="ChatText" name="ChatText">
</div>

You must set the parent container to position: relative;, and then set the child element to absolute.

Initially, the ChatBig has a height of 600px and the ChatText is 50px, so adjust the ChatMessages like this:

min-height: 498px; // avoid using height
position: absolute;
bottom: 50px; // matching the ChatText height of 50px

Next, for the ChatText, set it as follows:

position: absolute;
bottom: 0;

By doing this, the latest ChatMessages will stay at the bottom.

Note: The "qwe" text is simply used to mark the last line.

Answer №2

Can you explain the meaning of this particular line?

<input type="text" id="ChatText" name="ChatText"></textarea>

Should it actually be:

<textarea id="ChatText" name="ChatText"></textarea>

or maybe it should be:

<input type="text" id="ChatText" name="ChatText"/>

Answer №3

The solution is to include the max-height attribute.

.element
{
    max-height: 200px;
    overflow-y: auto;
}

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

Discover the potential of JavaScript's match object and unleash its power through

In the given data source, there is a key called 'isEdit' which has a boolean value. The column value in the data source matches the keys in the tempValues. After comparison, we check if the value of 'isEdit' from the data source is true ...

Instructions for utilizing a non-string reference without triggering flow errors

I've noticed that string refs are considered legacy in React. You can read more about it here: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-string-refs.md However, I am encountering a flow error in my component and I&apo ...

Exploring the TLS configuration for a Node.js FTP server project: ftp-srv package

I'm seeking to comprehend the accurate setup of TLS for my FTP project (typescript, nodejs) using this API: ftp-srv The documentation provided is quite basic. In one of the related github issues of the project, the author references his source code / ...

Accessing objects from a loop in JavaScript

In an effort to adhere to the principle of avoiding "polluting the global namespace" and due to the consensus that global variables are typically discouraged, I made a modification in my code by replacing global variables: stBgAsset15_src = $image.at ...

Is it possible for me to use the name "Date" for my component and still be able to access the built-in "new Date()" functionality?

Currently following the NextJS tutorial, but adding my own twist. In the NextJS example, the custom component is named "Date" (/components/date.js) and does not utilize the built-in Date() object in processing, making it unique to the file. In my scenario ...

Setting up route handlers in Node.js on a pre-initialized HTTP server

Is there a way to add route handlers to an http server that is already instantiated? Most routers, including express, typically need to be passed into the http.createServer() method. For instance, with express: var server = http.createServer(app); My r ...

extract the ng-model data and send it to an angular directive

In my current project, I have a specific situation where there are multiple text-boxes and when any of them is clicked, the corresponding ng-model should be displayed in the browser console. To achieve this functionality, I came up with the following Angul ...

What is the best way to access event.target as an object in Angular 2?

Apologies for my limited English proficiency. . I am trying to write code that will call myFunction() when the user clicks anywhere except on an element with the class .do-not-click-here. Here is the code I have written: document.addEventListener(' ...

Clicking on the button in Angular 2+ component 1 will open and display component 2

I've been developing a Angular 4 application with a unique layout consisting of a left panel and a right panel. In addition to these panels, there are 2 other components within the application. The left panel component is equipped with buttons while ...

Creating an external link in Angular with query parameters

I have created an app where users have their addresses listed, and I want to implement a feature that allows me to open Google Maps when clicking on the address. However, I am currently facing an issue where instead of getting the actual value of {{ this. ...

"Unlocking the Potential of ReactJS: A Guide to Setting Focus on Components Once They Become

My code had a <div> with a child component named SocialPostwithCSS, and when onClick was triggered, it would hide the div, set the state to editing: true, and display a <textarea>. I used this.textarea.focus with a ref={(input)=>{this.textar ...

Issue with CSS causing elements to display improperly within nested grids

I am facing an issue where I want to nest a grid within another grid, but the elements in the nested grid are not appearing in the order I desire. Specifically, I would like the "#classes" section to be at the bottom of the nested grid, but it remains stuc ...

necessitated in specified input with assigned value

Here is some code I have: <!DOCTYPE html> <html> <body> <form action="/action_page.php"> <select required> <option value=1>Volvo</option> <option value=2>Saab</option> <option value=3>Merc ...

Struggling with adding headers in React application

When I try to include an h1 heading, either the heading doesn't show up if I comment out the buttons, or if I comment out the heading, then the buttons don't display. But when both are included, nothing is displayed. Any suggestions on how to fix ...

Getting Checkbox Values with Laravel and jQuery

I am facing an issue where I am only able to retrieve one value from checkboxes in jQuery, even though multiple checkboxes have different values. Here is the code snippet: <form method="post"> @foreach($services as $service) ...

Error message: Object literal is limited to declaring existing properties

The source code was obtained from this Codesandbox demo: CodeSandbox - Cover Image Example Subsequently, an .eslintrc configuration file was generated with the following content (the only content present): { "extends": "react-app" } However, a TypeScri ...

Tips for incorporating Material.io outlined icons within css pseudoelements (::before) usage

I'm attempting to incorporate the Material.io icon into a button using ::before, but it is appearing filled rather than outlined. Unfortunately, there are no available instructions on how to display the icon in an outlined style. This is the code I ...

What is the best way to assign the order position in CSS?

I recently attempted to incorporate a CSS animated background into my project. Here is how it currently looks: The particle effect hovers above the menu list (which currently just says "test"). The CSS code for my particles is as follows: .circles { pos ...

Using Vue components or elements within the v-html directive allows for dynamic rendering

One of the challenges I'm facing involves handling data from a blog post, specifically the user-submitted text stored in post.text. Similar to Twitter, users can mention other users using syntax like I am tagging @user1 in this post. My goal is to aut ...

Limit Javascript Regex to accept only one specific possibility and exclude all others

Here are the specific validations I need for my URL: cars : valid cars/ : valid (Accepting any number of '/' after "cars") cars- : invalid cars* : invalid carsp : invalid (Rejecting any character after "cars" except '/') **cars/ne ...