Insert a fresh item to the end of the scrollable container

My goal is to dynamically add a div to the bottom of another div by using a JavaScript button click event. However, I have encountered an issue where once the outer container reaches its maximum height, the list no longer scrolls to the bottom after adding a new item.

To see the issue in action, you can check out this JSFiddle

If you repeatedly click the red add button until there are around 13 items in the list, it appears that the scrollTop function stops working correctly and the scroll position remains static.

I've experimented with various CSS configurations for both the container and the added div, but I'm still struggling to find a solution. Any assistance would be greatly appreciated.

Answer №1

I have adjusted your code to make it more jQuery-friendly. The main modification I made was to update the list.scrollTop() function so that it now scrolls to the bottom of list:

$(document).ready(function() {
    var list = $("#q-d-list");

    $(document).on('click', '#add', function() {
        $('.active', list).removeClass("active");

        var count = list.children().length + 1;
        var active = $('<div />', {
            'data-qid': count,
            'class': 'mli active'
        }).text('q' + count).appendTo(list);

        list.scrollTop(list[0].scrollHeight);
    });
});​

Check out the demonstration here: http://jsfiddle.net/MrvcB/19/

Answer №2

Implement

list.scrollTop(list.get(0).scrollHeight);

instead of

list.scrollTop($(".active").offset().top);

Answer №3

Check out this code snippet:

$(document).ready(function () {
var count = 2;

    $("#add").on("click", function () {
        var list= $("#q-d-list");

        // remove the active class from the old item
        var $clone = $(list.find("div:last-child").removeClass("active").clone());
        count+=1;

        var str_count = "q"+count.toString();
        $clone.addClass("active").attr("data-qid",str_count).text(str_count);
        list.append($clone);
        list.scrollTop(list.get(0).scrollHeight);        
    });
});

Click here to view the sample on jsFiddle!

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

Is there a way to use a single function to fill and calculate multiple input fields with PHP, Javascript, and

I've encountered an issue while trying to populate a form using Javascript/ajax/php. The problem is that my function only fills in one of the required forms and then stops, even though I have received the second response from the server. Here's ...

A guide on integrating the MUI Timepicker with the newest 6 version using Formik

I am currently experimenting with the MUI React Timepicker component and facing an issue during integration with Formik for validation. The problem lies in the inability to bind values properly in the initialValues of the form. const [initialValues, setI ...

Order of execution for setImmediate() and setTimeout() callbacks compared to I/O callbacks

In the world of Node.js, the event loop powered by libuv is divided into specific phases. The poll phase is where we wait for I/O tasks to complete before running their associated callbacks. The length of this waiting period is determined by timers, timeou ...

Should I open the Intel XDK hyperlinks in the default web browser instead of

Lately, I've been developing an HTML5 app on the Intel XDK that includes buttons linking to external websites. However, I'm encountering an issue where the apps open in the same window, leading users to get stuck in the browser. Currently, I am u ...

The best way to centralize the input group in bootstrap

I attempted to center align my search bar, but it stubbornly stays to the left. Here's the code I'm using: <head> <style> html { overflow: auto; } html, body, iframe { ...

Creating a dynamic image slider that smoothly glides across a webpage

I've been working on a carousel (image slider) for my website and I need some help. Specifically, I want to reposition the entire slider slightly to the left on the webpage. You can see the slider in action on this site: and I also created a jsfiddle ...

The React JSX error you encountered is due to the missing return value at the end of the arrow function

After implementing my code, I noticed the following: books.map(({ subjects, formats, title, authors, bookshelves }, index) => { subjects = subjects.join().toLowerCase(); author = authors.map(({ name }) => name).join() ...

The PHP for loop mysteriously adding an additional iteration

I'm currently working on solving a challenge. Within an unserialized array, I have multiple choice questions retrieved from the database and displayed in a dropdown menu. To properly grade the answers submitted by users, the system needs to loop thr ...

Discovering active path while utilizing dynamic routes - here's how!

Whenever I click on the project element in my HeadlessCMS with the URL /projects/slug-name, the projects button in my Navbar (LinkItem) does not highlight with a background color (bgColor). How can I modify this line of code: const active = path === href / ...

Exploring Typescript: Understanding the nuances of importing and exporting values or references

Currently, I am facing a challenge while converting Javascript code to Typescript, specifically with regards to import and export functionality: Intended Functionality: I aim to import 'POST_Requirements' into multiple other files. Each file tha ...

Could a commenting feature be seamlessly integrated directly into the video player, accessible with a simple click?

I'm exploring the idea of developing a video player that allows users to add comments directly from the player itself. Imagine this: the typical toolbar at the bottom includes standard features like seek bar, volume control, play/pause buttons, but wi ...

What is the process for changing a jQuery countdown function to a count-up function?

I'm currently developing a portal that utilizes a jquery plugin known as countdown from the link https://github.com/hilios/jQuery.countdown Here is the code snippet: $(document).ready(function(){ $("#countdown").countdown("2022/06/25 ...

Is it possible to set up a PHP variable within a JavaScript function?

In the code snippet above, we have a JavaScript function that is used for validation. I am looking to set a PHP variable within the else statement. function validate() { if(document.loginForm.vuser_login.value==""){ alert("Login Name name ca ...

Angular detects when a user scrolls on a webpage

I have developed a straightforward navigation system using Angular. The main controller is responsible for generating the menu. <nav class="{{active}}" ng-click= ""> <a href="#a" class="home" ng-click= "active='home'">Home< ...

What is the best way to make a JavaFX WebView the same size as the entire scene?

My goal is to have a JavaFX WebView that automatically resizes to fit the scene upon startup. Currently, I am focused on setting the initial size properly. @Override public void start(Stage stage) { try { Scene scene = new Scene(createWebViewP ...

Do you think it's wise to utilize React.Context for injecting UI components?

I have a plan to create my own specialized react component library. These components will mainly focus on implementing specific logic rather than being full-fledged UI components. One key requirement is that users should have the flexibility to define a se ...

Colorbox's functionality struggles to uphold several groups simultaneously without encountering errors

I have incorporated Colorbox on this page. On the setup, I have various groups listed as groups 1 to 9. However, when clicking on the second and third items, they display correctly according to the provided code. My aim is to make everything appear in the ...

Read in a CSV document within my JavaScript application

Is there a way to import a CSV file into my program in JavaScript when I know the file path? For instance, if the path to the CSV file is C:/Users/User/example.csv, I want to be able to load it into my program like this: let MY_CSV_FILE = CSV_LOAD("C:/Use ...

When attempting to add or store data in MongoDB, it triggers a 500 server error

Greetings, I am currently working on developing a CRUD app using the MEAN stack. The Express application loads successfully and retrieves the "contactlist" collection from the database. However, when attempting to make a POST request to "/api/contacts", an ...

Filtering arrays using Vue.js

I have developed a sample e-commerce website to showcase various products to potential customers. The website boasts features like filters, search functionality, and sorting options to enhance the user experience. However, I've encountered an issue sp ...