Is there a way to automatically scroll to the last dynamically added div?

Within the chat.html file, I have included a div tag and implemented a script that dynamically adds rows to the div when a button is clicked. In another file named list.html, I have inserted an iframe tag with the src attribute pointing to chat.html. However, upon loading the chat.html page, the div does not automatically scroll to the end, requiring manual scrolling instead. To address this issue, I aim for the div to auto-scroll to the end whenever new content is added.

//list.html page code
<body>
 <div class="row">
    <div class="col-lg-6 mx-auto mt-5">
        <iframe width="1000px" height="650px" src="EarlyChat.html" ></iframe>
    </div>
  </div>
</body>

//chat.html page code
<section style="padding: 50px 0 0 0">
 <div id="questions" style="margin-bottom: 85px !important;"></div>
   <div class="msg-box">
     <div class="form-group">
       <input type="text" class="input-box sty-one" id="message" placeholder="Enter message"> <button type="submit" class="btn btn-primary btn-lg mb-2" style="margin-top: 5px" onclick="sendmessage()">send</button> 
     </div>
    </div>
  </section>

function sendmessage(){
     db.collection("ChatRoom").doc(userid).collection("Cities").orderBy("Time")
     .onSnapshot(function(querySnapshot) {
        var store_row = document.createElement("questions");
        var store;
        $('#questions').empty();
        querySnapshot.forEach(function(doc) {
          typeofmessage = doc.data().SenderId;
                    time = doc.data().Time.toDate();
                    console.log("typeofmessage value is",typeofmessage,time);
                    message = doc.data().message;
                    
                    store = document.createElement("div");
                    if(typeofmessage == "Df"){
                       
                        leftids.push(message)
                       
                        store.setAttribute("class", "card no-border");
                        store.setAttribute("id", doc.id);
                        store.innerHTML = `<div class="container1 darker">
                                        <img src="assets/images/user1.png" alt="Avatar" style="width:100%;">
                                        <p class="text-left">` + message + `</p>
                                        <span class="time-left">` + time.getHours() + ":" + time.getMinutes()  + `</span>
                                        </div>`;

                    }
                    else if(typeofmessage == userid){
                        
                        rightids.push(message)
                       
                        store.setAttribute("class", "card no-border");
                        store.setAttribute("id", doc.id);
                        store.innerHTML = `<div class="container1">
                                        <img src="assets/images/image 209.png" alt="Avatar" class="right" style="width:100%;">
                                        <p class="text-right">` + message + `</p>
                                        <span class="time-right">` + time.getHours() + ":" + time.getMinutes() + `</span>
                                        </div>`;
                    }
                    store_row.append(store);
                   
                    document.getElementById("questions").innerHTML = store_row.innerHTML;

                });
            });
}

Answer №1

To make a specific div tag automatically jump when a button is clicked, you can include the id or name in the src attribute. Each div tag should have a different id assigned to it. Then, upon clicking the button, append the id of the last div tag to the iframe's src attribute in list.html as shown below:

<iframe width="1000px" height="650px" src="EarlyChat.html#message1" ></iframe> // assuming message1 is id of last div tag.

For further details, please refer to this source

Answer №2

To achieve this, you can utilize the window's scrollTo method along with the offsetTop property of the last div.

More on Window.scrollTo More on HTMLElement.offsetTop

I've simplified your example to demonstrate how it works. Here, I'm dynamically adding elements, storing the last element's offsetTop, and then scrolling to that position.

The only thing to note is that I had to introduce a setTimeout to ensure the new elements are properly added to the DOM.

<!DOCTYPE html>
<html>
    <body>
        <h1>Hello World</h1>
    </body>
    <script>
        // Simulate an array of data to render new content
        const paragraphs = []
        let lastParagraphY = 0

        for (let i = 0; i < 20; i++) {
            paragraphs.push(`This is paragraph ${i}. Lorem Ipsum...`)
        }

        // Dynamically create new HTML nodes
        paragraphs.forEach((paragraph, index) => {
            const body = document.querySelector('body')
            const newParagraph = document.createElement('p')
            newParagraph.innerHTML = paragraph
            newParagraph.id = index
            body.appendChild(newParagraph)
            lastParagraphY = newParagraph.offsetTop
        })

        // Ensure the dynamic elements have rendered
        setTimeout(() => {
            window.scrollTo(0, lastParagraphY)
        })
    </script>
</html>

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

Prevent mobile view from activating when zoomed in on the screen

I've built a webpage with a responsive design that adjusts to mobile view on mobile devices or when the screen size is reduced using developer tools. While this functionality works correctly, I have noticed that the design also switches to mobile vie ...

Is there a unique identifier associated with web explorers?

I'm conducting an experiment and I've noticed that Google is able to detect that it's the same computer, even when I change various settings. It seems to be identifying the explorer with a unique ID or something similar. I have tried everyth ...

Dividing the text by its position value and adding it to a fresh object

I needed to divide the paragraph into sections based on its entityRanges. Here is what the original paragraph looks like: { type: 'paragraph', depth: 1, text: 'Do you have questions or comments and do you wish to contact ABC? P ...

Is there a way to confirm that the content of two files is identical?

Currently, I am utilizing mocha/supertest/should.js for testing a REST Service. When I make a request to GET /files/<hash>, it returns the file as a stream. I am seeking guidance on how to use should.js to assert that the contents of the file are i ...

Do frameworks typically result in redundant CSS declarations?

Working on my latest Wordpress theme project, I have integrated the Bootstrap framework. One of the styles included in the Bootstrap CSS file is: input, textarea, .uneditable-input { width: 206px; } This style rule is causing issues with how my search ...

Mobile device accessing a video file twice in a row

Currently, I am in the process of developing my own DRM solution for video content. Each time an access is made to the actual video file, it goes through a verification process. For example, instead of streaming video.mp4 directly, it first passes through ...

changing the name of a variable within ng-include

Here is some important HTML code: <ng-include src="'app/views/order.html'"></ng-include> Within the scope of this ng-include, there is a variable called trade. The structure of the trade variable is as follows: var trade = { or ...

Dealing with an asterisk * in an id selector: what you need to know

My PHP code generates a series of buttons for users to click on, each button representing the grade of a student. Additionally, the PHP code also creates the jQuery necessary to enable a random selection of students based on the grade clicked: echo "<d ...

Exploring the capabilities of JavaScript on view variables in ASP.NET MVC3 Razor

Can a variable be initiated in a view using Razor and then have its value manipulated using jQuery, or vice versa? ...

Are Opera and IE9 blocking cross-origin Ajax requests?

I have been utilizing the following page - - to initiate a cross-origin Ajax request towards this specific resource: The functionality appears to be functioning as expected in Chrome, Safari, and Firefox, but encounters an issue in IE9 and Opera. Below ...

Is it possible to remove the "disabled" attribute using JS, but the button remains disabled?

There are two buttons on my page: the first one is currently disabled, and the second one is supposed to enable the first button. That's the plan. Button 1: $(document).ready(function() { $('#click').click(function() { document.getE ...

Unusual behavior in a for loop with node.js

Trying out some new things with node.js and running into issues with a basic for loop... for (var i = 0; i < 5; i++); {( console.log(i)) } Can anyone explain why I'm seeing 5 in the console? I was anticipating 0,1,2,3,4... ...

What is the best way to determine if two external values are equal within a mongodb criteria object?

Consider the following collection: {id: 1, name:"abc"}, {id: 2, name:null} When testing a property, I typically use this method: db.collecton.find({name:"abc"}, {name:1}); // This will return the first document. Now, I want to incorporate two external ...

Should we be validating passwords through mongoose middlewares - is this the right approach?

I am currently using the validator package for email validation in my project. const validator = require('validator'); email: { type: String, required: [true, 'User must have a email'], unique: true, lowercase: true, / ...

The issue in AngularJS 1.4 where the select element value is not binding due to a type mismatch

My ng-model has a value assigned to it, but it is not binding with the selected element. <select data-ng-model="myval"> <option value="? number:2 ?"></option> <option value="2" class="ng-binding">Value 1</option> <op ...

The use of `preventDefault()` in React for the `onCopy` event is ineffective

I'm currently exploring ways to prevent the clipboard events from copying text when the onCopy event is triggered. I've tried using the onCopy handler and e.preventDefault() method, but the text is still being copied without any issues. What am I ...

How can I ensure that my user responses are case-insensitive?

Currently, I'm facing a roadblock in my coding journey. I am trying to modify my code so that user responses are not case sensitive when compared for correctness. Can anyone offer some advice on how to achieve this? Check out the code snippet below: ...

Consistent column heights within each row

I currently have Bootstrap implemented on my website and have integrated jQuery to adjust the height of each column to match the tallest one. However, the issue I am facing is that the height adjustment applies globally across the entire page, rather than ...

Incorporating an npm reference into a personalized node within Node-RED

As a novice in both the NodeRed and NodeJs/npm realms, I am embarking on the journey of creating a custom node for the first time. Despite my efforts to follow the official documentation on Creating your first node, I seem to have hit a roadblock. Everyth ...

Exploring jQuery Animation Effects: Enhancing Your Web Experience with Zoom In and Zoom Out

Is there a way to animate a logo using jQuery automatically upon page load? I want the image to zoom out, then zoom in and change to a different image. Can someone please assist me with this task? Below is the code snippet that I have: $(document).ready ...