What is the best way to remedy the bottom scroll issue?

I am currently working on a Messaging system and I need the scrollbar to stay fixed at the bottom so that when new data arrives, it automatically scrolls down. How can this be achieved using HTML/CSS? Please ignore any unprofessional formatting in the code provided.

https://i.sstatic.net/FJhFJ.png

Home.php

<?php
// Disabling error reporting
error_reporting(0);
    // Preventing non-logged-in users from entering
    if(isset($_SESSION['id'])){
        $user_id = $_SESSION['id'];
    }else{

    }

require_once("./inc/connect.inc.php");
?>

<header>
    <link rel="stylesheet" href="home - Copy.css" />
        <nav>
            <h3><a class="h3" href="#">CP</a></h3>
            <div><a href="logout.php"><span>Logout</span></a></div>
                <div>        
                        <?php

   // Starting the session
   session_start();
   // Reading the session (if set)
   if (isset($_SESSION['user_login'])){

 echo '<div id="ull">'.strtoupper($_SESSION['user_login']).'</div>';
         }


       ?>

                    </div>
        </nav>
        <body>
        <div class="shead">
        <div class="a1">       <li   >Frequent Member</li>
        <div class="fm">
             <ul>
                <?php

                    // Displaying all users except me
                $user_id = $_SESSION['id'];
                    $q = mysql_query("SELECT * FROM `users` WHERE id!='$user_id'");
                    // Displaying all results
                    while($row = mysql_fetch_assoc($q)){
                        echo "  <div class='usernames'>



                        <a id=\"usernames\" href='home.php?id={$row['id']}'>{$row['username']}</a>
                                </div> 
                        ";
                    }
                ?>
            </ul>
            </div>
        </div>


    <div class="a2">      <li >Site's Popular in Your College</li></div>

        </div>
</header>

...

<body>
    <div class="rss">

    ...

<script type="text/javascript">
var objDiv = document.getElementById("display-message");
objDiv.scrollTop = objDiv.scrollHeight;
</script>

    ...

<script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="js/script.js"></script>
</body>

Getmsg.php

 <?php
require_once("./inc/connect.inc.php");
if(isset($_GET['c_id'])){
    // Retrieving conversation id and messages based on user ids
    $conversation_id = base64_decode($_GET['c_id']);
    
    ...

?>

Answer №1

If you're using jQuery, you can achieve the desired behavior by following these steps:

$('#your_div_id').scrollTop($('#your_div_id')[0].scrollHeight);

Alternatively, if you are only using JavaScript, refer to this link for a solution: How to Scroll to Bottom of Div?

Remember to set the scroll option to the height of the div in order to keep it anchored at the bottom. Make sure to trigger this function when a new message is received and displayed.

Answer №2

Your solution is based on utilizing the scrollHeight property. Here are a couple of lines of code that can assist you:

var objDiv = document.getElementById("toScrollBottom");
objDiv.scrollTop = objDiv.scrollHeight;

You can test this snippet by clicking on the blue div to simulate adding messages.

var count = 0;
var objDiv = document.getElementById("toScrollBottom");
objDiv.scrollTop = objDiv.scrollHeight;
$("body").on("click","#toScrollBottom",function(){
  $("#messages").append('<p>Message Line' + count + '<br/>Message line</p>');
  var objDiv = document.getElementById("toScrollBottom");
  objDiv.scrollTop = objDiv.scrollHeight;
  count++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="toScrollBottom" style="height: 150px; overflow-y: scroll; margin: 50px; border: solid 2px blue;">
  <div id="messages">
    <p>Message Line FIRST<br/>Message Line</p>
  </div>
</div>

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

"Missing the import of material-ui search icons is causing a functionality issue

import React from 'react' import {Search} from "@material-ui/icons/Search" const App = () => { return ( <div> <Search/> </div> ) } export default App The exported component 'Search' (impor ...

Four unique classes will each be styled differently using pseudo selectors

Consider using this specific markup - it cannot be altered (Even though it would be simpler to add more classes or IDs). There will always be a maximum of six class "test" elements on the page, so the code can be written without certainty of their surroun ...

Tips for positioning bootstrap dropdowns side by side in a row

I'm having trouble aligning my li items in a Bootstrap dropdown next to each other. I've tried everything but nothing seems to work. Here's my code: <nav class="navbar navbar-expand-lg navbar-light bg-light"> < ...

The discovery of a commitment in the statement. The automation of unwrapping promises within Angular statements has been phased out

Struggling with errors while setting up a new AngularJS project. Here is the code for my app and controller; var app = angular.module('myApp', ['localytics.directives']) .config(['$parseProvider', function ($parseProvide ...

A single click causes the entire row of cards to extend seamlessly

The cards on this tab were generated using a loop and the data is sourced from a database. When I click on the "Show More" button, the entire visible column expands along with it. The expansion does not reveal the content immediately; instead, the content ...

Leaflet Alert: The number of child elements is not the same as the total number of markers

Encountering a problem with Leaflet clustering using v-marker-cluster. Within the icon createFunction of the cluster, the className of children is used to determine the cluster style. Here is a snippet of this function : const childCount = marker_cluster._ ...

Checking if multiple text fields with identical names are valid using BootstrapValidator

I'm facing an issue where I am unable to validate multiple text fields with the same name. The validation only works for the first input text field, but not for the rest. <form id = "frm_org_id"> <input type="text" name="email_address[]" pla ...

The dependency path in the package.json file contains all the necessary files

I recently developed a JavaScript package and here is the configuration in my package.json: { "name": "packageName", "version": "1.0.0", "description": "Description of the package", " ...

Retrieving the country code using Google Maps in conjunction with HTML 5 GeoLocation

I've been working on a project that involves using HTML 5 GeoLocation to retrieve longitude and latitude coordinates, and then utilizing the Google Maps API to obtain the corresponding country code based on those coordinates. However, I seem to be enc ...

Having trouble getting the AJAX script to change the background in Internet Explorer?

I'm currently experiencing an issue with an ajax script. Here is the code I am using: <script type="text/javascript"> $(document).ready(function() { $('#savecolor').click(function(){ var myVar = 'data= ...

Click to dynamically toggle classes with jQuery

I am trying to apply a class called 'select' when I click on a paragraph tag. However, the code I have written doesn't seem to be working. Can someone please provide some suggestions? Here is the code: <style type="text/css"> #el ...

Is it possible to create an index for an associative array based on a string in JavaScript?

Within my JavaScript code, I am working with an associative (two-dimensional) array (myObj[x][y]). Each row in this array contains a different number of elements denoted by 'n', where the first value signifies the amount 'n' as shown be ...

When there is no content in the responseText, AJAX will display an error

I've encountered an issue while trying to fetch data using AJAX. The problem lies in receiving an empty responseText. Here's the code I'm working with: JavaScript: function getFounder(id) { var founder = ""; $.ajax({ ...

Having trouble getting a DIV to appear on top of another DIV containing an image

I need help with positioning an "InfoBox" above the main header image on my website. Despite trying z-indexes and adjusting position, I can't seem to get it right. If anyone has any suggestions, please share. Thank you! For reference, here is the HTM ...

Position a button to be aligned with the bottom of its container

My goal is to have the button positioned at the bottom of the red div, nested inside it. .grand-parent { display: flex; flex-direction: row; flex-wrap: wrap; height: 300px; background-color: green; } .pa ...

In jQuery, turn off the hover function while the animation is in progress

I've implemented this jQuery animation: $('.menu1').stop().animate({left: "29%", top: '2%', width:'40%', fontSize: '60%'}, 3000); $('.menu2').stop().animate({left: "44%", top: &apo ...

Current recommended method for updating innerHTML with properly formatted text?

My understanding is that using innerHTML on an element can be risky, as malicious users could potentially inject harmful content such as <script> tags. This question shows there are multiple alternative tags, some of which are non-standard. In my s ...

Enhance your web design skills by customizing Bootstrap5 framework styles using the @layer feature

Here is the HTML code I am working with: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name=& ...

Tips on extracting JSON subcategories?

I am currently attempting to retrieve information from a local JSON file using the following JavaScript script: let accordion=document.querySelector('#accordion'); fetch('countries.json') .then(function(response){ return response.js ...

Effortless scrolling implementation

How can I make the scroll smooth and animated with this code structure? Check out my JSFiddle here: https://jsfiddle.net/v7qhzo8q/ The code structure is as follows: <nav id="nav"> <ul id="top"> <li><a href="#">Home</a> ...