Dynamically injecting divs into a webpage's left side using JavaScript

Currently, the div's are being added from the left side and moving to the right. How can I change it so that the div's are added from the left? This way, the first card will appear in the middle and new cards will stack up behind it to the left.

I attempted using float: right, but it did not produce the desired outcome.

var parentEl = document.getElementById("cards");
var elem = document.getElementById("myBar");
var width;
var id;



var parentEl = document.getElementById("cards");
var elem = document.getElementById("myBar");
var lastCard;
var width;
var id;



function sortCards() {
  var cards = document.getElementsByClassName("card"),
      cw = parentEl.clientWidth,
      sw = parentEl.scrollWidth,
      diff = sw - cw,
      offset = diff / (cards.length - 1 );

     for (var i = 0; i < cards.length; i++) {
       i != 0 && (cards[i].style.transform = "translateX(-" + offset * i + "px)");
     }
}

//Move card
document.getElementById("moveCard").addEventListener("click", function () {
    myMove();
});


//Start the game
document.getElementById("play").addEventListener("click", function() {
        move();
});

//Stop the game
document.getElementById("stop").addEventListener("click", function() {
    stop();
});

function move() {
    width = 1;
    id = setInterval(frame, 5);
    function frame() {
        if (width >= 100) {
            elem.style.width = 1 + '%';
            clearInterval(id);
            addCard();
            move();
        } else {
            width++; 
            elem.style.width = width + '%'; 
        }
    }
}


function myMove() {

    var elem = lastCard;
    lastCard = lastCard.previousSibling;

    var pos = 0;
    var id = setInterval(movie, 5);
    function movie() {
        if (pos == 350) {
            clearInterval(id);
            elem.remove();
        } else {
            pos = pos + 5;
            elem.style.top = pos + 'px';
            elem.style.left = pos + 'px';
        }
    }


}

function addCard(){
  var div = document.createElement("div");
  div.style.position = "relative";
  div.style.color = "green";
  div.style.left = "auto";
  div.classList.add("card");
  parentEl.appendChild(div);
  lastCard = div;
  sortCards();
}


function stop() {
    elem.style.width = 1 + '%';
    clearInterval(id);
}

sortCards();
.cards {
  display: flex;
  max-width: 300px;
}

.card {
  height: 90px;
  border: 1px solid black;
  border-radius: 3px;
  background-color: rgba(255, 0, 0, 0.4);
  flex: 0 0 50px;
  background: red;
  transition: transform .25s;
}

.cardGreen {
 height: 90px;
  border: 1px solid black;
  border-radius: 3px;
  background-color: rgba(255, 0, 0, 0.4);
  flex: 0 0 50px;
  background: green;
  transition: transform .25s; 
}

#myProgress {
    position: relative;
    width: 100%;
    height: 10px;
    background-color: grey;
}
#myBar {
    position: absolute;
    width: 1%;
    height: 100%;
    background-color: green;
}

/* Create three unequal columns that floats next to each other */
.column {
    float: left;
    /*padding: 10px;*/
    height: 300px; /* Should be removed. Only for demonstration */
}

.left, .right {
    width: 20%;
}

.middle {
    width: 60%;
}

/* Clear floats after the columns */
.row:after {
    content: "";
    display: table;
    clear: both;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
        <link rel="stylesheet" href="style.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
        <header>
            <h1>Simple game</h1>
        </header>

        <div class="row">
            <div class="column left" style="background-color:#aaa;">
                <div><button class="btn btn-default btn-block" id="play">Start Game</button></div>
                <div><button class="btn btn-default btn-block" id="stop">Pause</button></div>

                <div><button class="btn btn-default btn-block" id="moveCard">Move Card</button></div>
            </div>
            <div class="column middle" style="background-color:#bbb;">
                <div class='cards middle' id="cards">
                    <!--<div class='cardGreen'></div>-->
                </div>
                <div id="myProgress">
                    <div id="myBar"></div>
                </div>
            </div>
            <div class="column right" style="background-color:#ccc;">

                <h2>Tutorial</h2>
                <p>Will be here soon :)</p>
            </div>
        </div>



        <script src="gamelogic.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    </body>
</html>

Any advice or suggestions would be greatly appreciated.

Answer №1

If you want to insert an element at the beginning of the parent instead of the end, you can use the prepend method instead of append.

parentEl.prepend(div);

The ParentNode.prepend method inserts a set of Node objects or DOMString objects before the first child of the ParentNode.

However, this won't automatically center the first card on the screen. You will need to adjust the positioning of the cards accordingly.

...

EDIT:

To ensure the first card appears in the middle, set the parent's width to 0% and increase it each time a card is added until it reaches 100%. Also, add margin: 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

Error in JSON data structure while transferring data from Jquery to PHP

Having some trouble with my first attempt at sending a JQuery request to an API I'm developing. My PHP code keeps reporting that the JSON is malformed. Interestingly, if I create a JSON array in PHP and send it through, everything works perfectly. Bu ...

Using jQuery to target and select a specific div element by its class

Could you please guide me on how to use jQuery to select the value of the second class in a div element? For example; <div class="mb-20"></div> Is there a way to extract just the "20" from the "mb-" class name? ...

Having trouble with the border in Tailwind CSS after integrating Flowbite?

Inside this div is where my component is wrapped: <div className="bg-gray-800 border border-gray-700 rounded-lg"> .... </div> When I installed Flowbite, the border color didn't show up as expected. Check out the borde ...

Add to an array the recently created span element which was inputted through text in AngularJS

Having some difficulty controlling an array object with a list of span values using a watcher in Angularjs. The current setup works partially - when I input span elements, an array is automatically created for each span. When I remove a span element, the ...

The feature in DataTables that allows users to choose how many items to display per page is not functioning correctly

My DataTable is experiencing issues with the box that allows you to select how many items per page you want to show. Instead of displaying just the numbers, it shows: [[5,10],[5,10]]. I have tried to troubleshoot this problem without any success. Addition ...

How to make text in HTML and CSS stay at the bottom of a div?

I am in the process of creating a website dedicated to my "Starcraft II" clan. My goal is to have the navigation bar display the text "ALLOYE" and remain fixed at the bottom of the screen. I attempted to achieve this using the following code: vertical-alig ...

Optimal method for storing text descriptions across two platforms (react native and react)

Hello, I hope you are doing well. I have a question regarding two platforms that I am using - React Native and React (NextJS). Both platforms have forms to save data, one of which is a "text description." Here's the issue: When I input a long passag ...

Turning text into clickable links using JavaScript

I am faced with a scenario where I need to detect phone numbers within a string and convert them into clickable links. At the moment, using an external library is not an option. Here's the progress I've made so far: String: "This is my phone nu ...

Is there a way to automatically redirect the main html page to a different html page upon logging in?

I have created a main page in HTML with a login box that displays a message saying "Login successful" or "Login failed" based on whether the password entered is 8 characters or more. The validation function for this works correctly, but after successfully ...

How to load several stylesheets for a component in Angular 2

Struggling with my angular2 application, I encountered an issue when attempting to load multiple stylesheets for the same component. Below is a snippet of the code: import { Component } from '@angular/core'; @Component({ selector: 'my-tag& ...

Catching the Selenium NoSuchElementError in JavaScript is impossible

Update: It's puzzling why this was marked as answered since the linked questions don't address the issue at hand and do not involve Javascript. My objective is to detect this error, rather than prevent it, given that methods like invisibilityOfEl ...

Encountered an error while trying to retrieve data from

Having trouble with file uploads to the S3 bucket using @aws-sdk/client-s3 library and encountering errors when uploading files larger than 70kbps: `TypeError: Failed to fetch at FetchHttpHandler.handle (fetch-http-handler.js:56:13) at PutObjectCommand ...

Is there a way to make the <iframe> adjust its size as the element it contains grows, without

Seeking assistance with a specific issue. My goal is to have an iframe appear on hover of another element and expand with it. The problem I'm facing is that the iframe shows up quickly and extends beyond its parent container. Here's what I have: ...

Determine whether all elements in the array are false using Array.every()

Below is an example of an array: myArray = {firstValue: false, secondValue: false, thirdValue: true, forthValue: false}; The goal is to determine if every value in the array is false. If that condition is met, then perform a specific action. For instance ...

Real-time update of quiz results based on varying factors

In my quiz, I have set up variables that start at 0 and increase based on certain conditions. One variable should increase when a question is answered correctly, while the other should increase when a question is answered incorrectly. If you answer a quest ...

Here's the step-by-step process: Access the specific item in the object by referencing `obj[i]["name of desired attribute"]

I tried seeking advice and consulting multiple sources but none provided a suitable answer. Is there someone out there who can assist me? obj[i].["name of thing in object"] Here's the array: [ { "name": "DISBOARD#2760" ...

Content not refreshing when closing and reopening Highslide iframe

I am encountering an issue with Highslide where I am unable to reopen a popup with new content. Even though the contentId remains the same, the content is not being updated when the popup is reopened. Below is the code snippet that showcases the problem: ...

How come the transition does not take effect when removing and adding the class to the same element with the removeClass() and addClass() methods?

Two images are present, with the first one having the class "opacityOne". When a button is clicked, based on the variable index, I want the current image to fade in while the other fades out. It works well when I remove the "opacityOne" class from one ima ...

Shut down the Pub/Sub client following a transmission via socket.io-mongodb-emitter

I am facing an issue with emitting a message into a socket.io room using socket.io-mongodb-emitter. The problem lies in the fact that my script never exits as it maintains a connection to mongodb. Take a look at the examples below and provide some suggest ...

Toggle the visibility of HTML elements by utilizing a JavaScript checkbox event

I have put together these JavaScript functions to hide the delivery address fields on my shopping cart address form if the goods are being sent to the billing address. The functions control the visibility of the HTML wrapped by... function getItem(id) { ...