Issue arises when implementing an animation to slide a div to the right followed by dynamically inserting a new div

I have a container div and an array. Initially, I prepend 3 divs to the container div. Then, after a delay of 3 seconds, I remove the 3rd div. Using jQuery animate, I transition the 2 remaining divs to the right side before adding a new div.

The issue arises when the newly added div does not appear in the desired location, causing a large space between it and the remaining 2 divs. Additionally, a vertical scroll bar unexpectedly appears.

$(document).ready(function()
{
    addBoxes();

    setInterval(function() { removeBox(); }, 3000)
});

var boxArray = [
    {name: "Box 1",},
    {name: "Box 2",},
    {name: "Box 3",},
    {name: "Box 4",},
    {name: "Box 5",},
    {name: "Box 6",},
    {name: "Box 7",},
    {name: "Box 8",},
    {name: "Box 9",},
    {name: "Box 10",},
    {name: "Box 11",},
]

function addBoxes()
{
    for (var i = 0; i <= 2; i++)
    {
        $(".container").prepend("<div class='box animated fadeInLeft faster'>"+ boxArray[i].name +"</div>");
    }

    boxArray.splice(0, 3);
}

function removeBox()
{
    if (boxArray.length === 0)
    {
    }
    else
    {
        var card = $(".container .box:nth-child(3)");
        card.addClass("animated fadeOutRight faster").one(function()
        {
            card.unbind().remove();
        })

        //addSingleBox();
        animateRemainingBox();

        setTimeout(function()
        {
            addSingleBox();
        }, 400)
    }
}

function addSingleBox()
{
    $(".container").prepend("<div class='box'>"+ boxArray[0].name +"</div>");
    boxArray.shift();
}

function animateRemainingBox()
{
    $(".box").animate({left: $(".box").width()})
}
.container {
    margin: 0px;
    padding: 0px;
    width: 100%;
    height: 100%;
}

.box {
    height: 80%;
    width: 32%;
    border: 1px solid black;
    border-top-right-radius: 20px;
    border-top-left-radius: 20px;
    background: rgb(239, 242, 244);
    box-shadow: 4px 8px 16px #808080;
    display: inline-block;

    position: relative;
    overflow: hidden;
}

.box:nth-child(2) {
    margin-left: 1.7%;
    margin-right: 1.7%;
}

.box:nth-child(1) {
    margin: 0px;
}

.box:nth-child(3) {
    margin: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
</div>

Answer №1

Experiment with adding a hidden static element after the 3rd div, giving it an ID of your choice. Implement a JavaScript function that dynamically adds the next div using .insertBefore(). The function takes the ID of the static element as its argument.

selectedContainer = document.querySelector('#selectedContainerId')
staticElement = document.querySelector('#yourHiddenElementId');
selectedContainer.insertBefore(newDiv, staticElement);

This technique can be considered as a form of safeguarding when working with JavaScript, as sometimes things just won't work without any clear explanation.

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

Using Jquery to Parse Json data from Twitter

I am currently facing an issue where the system is producing too many results despite working properly. Any suggestions on how to resolve this? var url = "search.twitter.com/search.json?q=%23ps3&rpp=15&from=mmgn&lang=en&callback=?"; $.getJSON(url, funct ...

Guide to verifying a METHOD GET request with Node.js and Express

Issue I've developed an API that returns an array of data when a request is made. The API URL needs to be accessed by an external team of developers. My goal is to restrict access to the /api/verily endpoint only to this specific team. Is there a wa ...

Could the absence of an external style sheet for CSS be hindering the execution of my code?

A generous Stack Overflow user provided me with the code you see here and their JSFiddle can be accessed at http://jsfiddle.net/f18513hw/. The code functions properly in JSFiddle. I copied and pasted the code into my Textpad, saved it in my htdocs folder o ...

IonTabButton not responding to onClick events

Currently, I am utilizing the Ionic 5 CSS library in combination with React. I found that IonTabButtons have a more appealing style compared to IonButtons because IonTabButton allows for text below the Icon. In the screenshot provided, all icons are displ ...

Refresh stock value in anychart without having to re-render the entire chart

I am currently experimenting with the Anychart stock candlestick chart and I must say, it is quite impressive. However, I have encountered an issue while trying to update the chart using a setInterval function. The problem is that it re-plots the entire ch ...

KnockOut.JS compares two arrays and removes the distinct values from the second array

I've been diving into Knockout.js and I have a question. var chosenFruit = ko.observableArray([]); var allFruits = ko.observableArray([]); allFruits = [ "Apple" , "Bananna" , "Grapes" , "Oranges"] chosenFruit = ["Apple" , "Ba ...

Issue with Bootstrap 4 column width when using Angular 2 *ngFor

I have a container that displays search results. The layout is set up using Bootstrap columns, but there seems to be excessive padding or margin causing the results to appear very narrow. Interestingly, if I manually input each result instead of using *ngF ...

transmitting specific data entries to a controller through jQuery's jtable

I am looking to extract multiple records from jtable and transmit them to my spring controller. Here is what I have accomplished so far: HTML <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> < ...

Introducing unspecified margin above a bootstrap 3 affix/scrollspy component

Check out this link to see the navigation with affix and scrollspy functionality as you scroll down (using bootstrap 3): http://codepen.io/datanity/pen/thnua Adding white space at the top causes the affix/scrollspy to trigger in the wrong location. For e ...

How to Identify onmouseout in Google Gadget without an event attribute within HTML

I am in need of a JavaScript method that can identify when the mouse exits an element with the id="myDiv" within an if() clause. Unfortunately, I am unable to utilize the JS onmouseout event directly in my HTML. It is essential for me to be able ...

Exponential calculator in Javascript

I'm working on a basic calculator project using html5, css3 and javascript. However, I've run into an issue with the exponent button not functioning properly. Here's my code snippet: <html> <head> <meta charset = "utf-8" ...

Population of the global namespace in JavaScript without the need for the 'new'

After watching the Douglas Crockford video on JavaScript, one thing that caught my attention was his explanation of what happens when you forget to use new for a class. He mentioned that doing so would populate the global namespace, which in the browser is ...

limited growth of float variable

I am utilizing CSS code to create column a and column b, using float in the code to dynamically expand column a as content is added to column b. However, this expansion is not occurring as expected. To see my code, please visit http://jsfiddle.net/hadinetc ...

What is the purpose of the 'new' keyword in JavaScript?

After years of using JavaScript like a semi-imperative version of Lisp, I am still confused about how constructors actually work in the language. I would appreciate some insight into how objects are meant to function in JavaScript. Consider this code snip ...

Difficulty with integrating DIVs with floating SPANs

My current form is very basic and includes the following: <div class="datepicker"> <p> From: <span class="spanMonth"> <div id="div_dateFromReports_month"> <select></select> ...

Input fields that are dynamically generated do not respond to changes made using .click and .blur methods in jQuery CSS

I'm experiencing an issue with a HTML form where a new input field is generated when a button is clicked, but the dynamically created field is not styled properly. Below is the HTML form code: <form id="form"> <input type="text" id="ent ...

Determine the presence of a username and email in the MongoDB database

I am currently updating my code to validate if both the username and email already exist in my MongoDB database before adding a new user. Currently, the code successfully checks for existing emails but I am struggling to implement a check for usernames as ...

Effectively handling memory usage in dynamically loaded JavaScript pages

I am facing a dilemma and seeking advice on the best approach to deal with it. While developing a single-page web application, I have implemented a system where pages are dynamically loaded via ajax, requiring each page to have its own corresponding javasc ...

Discover how to initiate mention recommendations in AngularJs similar to Facebook's like function without the need for a trigger character such as '@'

I have integrated the third-party library mento.io into my project to meet my requirements. You can find the library on Github. This library currently displays suggestions after a specific character input, but I need it to provide suggestions as soon as t ...

Is it possible to use jQuery and .load() to dynamically refresh multiple div elements with different unique IDs?

Currently, I am in the process of customizing a plugin to enable users to vote on posts. The layout of my page resembles this structure (albeit simplified): <div class="vote vote1"> //voting buttons </div> <div class="vote vote2"> //vot ...