An element generated using a JavaScript loop is covering another element in the layout

I am facing an issue with positioning images within a div to a span. The problem arises as the images are overlapping each other and I am uncertain about how to properly place each image when it is added.

Below is the code snippet:

The CSS:

<style type="text/css">
        body{background-image:url('image/wood.jpg');}
        h1, h3, h4, h5, h6, p{text-align:center; font-family:helvetica; font-weight:900;}
        h3, h4, h5 {color:red;}
        h1, h6, p{color:white;}
        img{height:120px;}
        span{display:inline-block; margin-left: 25px; height:250px;}
        div.inv{background-image:url('image/shelf.jpg'); background-position:fixed; 
            background-repeat:none;}
        span#la, span#me, span#sm{margin-left:auto; margin-right:auto; width:800px;}
        div{background-image:url('image/crate.jpg'); margin-left:25px; 
            margin-right:25px;}

The Javascript:

var temp = null;
        var largeArray = new Array(6);
function isTemp()
        {
            if(temp == null)
            {
                alert("Please pick an item to place in the container");
            }               
        }

function fillLarge()
        {
            isTemp();
            if(largeArray[0] != undefined &&largeArray[1] != undefined &&largeArray[2] != undefined && largeArray[3] != undefined &&largeArray[4] != undefined &&largeArray[5] != undefined)
            {
                alert('This crate is full');
            }
            else
            {
                for (var i=0; i<6; i++)
                {
                    if (largeArray[i] == undefined)
                    {
                        largeArray[i] = "<img src='image/"+temp+".jpg'/>";
                        document.getElementById("la").innerHTML = largeArray[i];
                        break;
                    }
                }
                document.getElementById(temp).style.display="none";
                temp = null;
            }
        }

The HTML:

<div>
    <h3> LARGE CONTAINER </h3>
    <span id="la" onclick="fillLarge();"> 
    </span> </div>
<span id = "gold" onclick = "temp = this.id;">
                <img src="image/gold.jpg"/>
                <p> Gold that you didn't farm </p>
            </span>
            <span id = "Moarg" onclick = "temp = this.id;">
                <img src="image/Moarg.jpg" />
                <p> Mo'arg Slave for <br /> your engineering needs </p>
            </span>
            <span id = "sweetroll" onclick = "temp = this.id;">
                <img src="image/sweetroll.jpg" />
                <p> Sweetroll stolen from a citizen </p>
            </span>
            <span id = "uranium" onclick = "temp = this.id;">
                <img src="image/uranium.jpg" />
                <p> Uranium Ore </p>
            </span>

I have basic knowledge of javascript but haven't used jQuery or any advanced techniques before.

Answer №1

The issue lies in your JavaScript code...

Instead of adding each image, you are replacing the inner HTML with the new image.

To resolve this problem...

document.getElementById("la").innerHTML = largeArray[i];

Change it to...

document.getElementById("la").innerHTML += largeArray[i];

(Make sure to use "+=" to append the new HTML content)

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

Troubleshooting: Images not appearing on HTML pages

I've recently started learning HTML and can't figure out why my code isn't working. I am trying to add an image but it only appears as a blue box with a question mark in it. Here is my code: <head> <title>Welcome</title> ...

Utilizing React with a Bootstrap Select element populated by an API call. Following form submission, I aim to automatically deselect the previously selected

After submitting the form, I am trying to reset the state to an empty value for the dropdown menu, but the selected item still appears before submitting the form. Any assistance in identifying the issue would be greatly appreciated. Thank you. Please see ...

What is the best way to maximize the width of this element?

Check out my website: There's a div styled with the color #D9D9D9 This is the CSS code: #full_bar { background: #D9D9D9; width: 100%; height: 100px; } I want the div to span across the full width of the website and be stuck to the footer. An ...

Tips for correctly saving an array to a file in node.js express using fs module

I have been attempting to write an array to a file using node.js and angular for assistance, you can refer to the provided code in this question. Whenever I send the array, the file displays: [object Object],... If I use JSON.stringify(myArr) to send my ...

Developing a fresh instance in JavaScript

Currently, I am working with a JSON object that I'm required to use in my project. const template = require('../../../../assets/jsons/article-tpl.json'); Next, I need to iterate through an array and utilize this object to generate a new te ...

Mastering the Art of Merging 3 Arrays

Greetings to the Community I have a question regarding my code. I am looking to merge three variables together. $result = mysqli_query($con, "SELECT disease,age,SUM(CASE WHEN gender = 'm' THEN 1 ELSE 0 END) AS `totalM`, SUM(CASE WHEN gender ...

What is the best way to utilize static methods for transferring authentication tokens to an API class?

Recently, I developed an API class to handle network calls in redux saga. The structure of the class is as follows: export default class ApiService { constructor(bearer) { this.instance = axios.create({ ... ...

Develop fresh JavaScript code using JavaScript

Is it possible to dynamically create a new row in an HTML table by clicking on a button? Each row contains multiple input fields. <script type="text/javascript> row = 2; specific_row_id = new Array(); $(document).ready(function() { $(".change_1 ...

Encasing the app component with a context and encountering the issue: TypeError - (destructured parameter) does not have a defined value

My goal is to wrap all components under the app in a context to provide specific functionalities (as evidenced by my UserContext component). import React, { useState, createContext, useContext } from 'react' const Context = createContext(); exp ...

Utilizing CSS classes to style custom day templates in ng-bootstraps datepicker

Currently, I am utilizing ng-bootstraps datepicker to showcase user data on a daily basis. I have implemented a custom day template to apply specific CSS classes. <ng-template #customDay let-date> <div class="custom-day" [ngCla ...

Above the search box in jQuery Datatable's search box, there is search text displayed

My datatable looks like this: var exTable1 = $("#exTable").DataTable({ "language": { "search": "Filter", "searchPlaceholder": "search", "loadingRecords": "", }, data: datasrc "dom": '<"top"lf>rt<"botto ...

Error: The file could not be read due to an IndexError, as the list index is out of range

Creating a word storage and reader tool based on user input is my current project. Think of it as a personal dictionary. Here's my code: if path.exists("data/inputs/" + word2 + ".txt"): file = open("data/inputs/" + word2 + ".txt", "r") for l ...

What is the best way to apply CSS max-left or min-left positioning to an absolute element?

I currently have an element with the CSS properties: position:absolute; left: 70%; Is there a way to restrict this element from moving more than 900px from the left side? Similar to max-width but for positioning? ...

Struggling to make cookies stick in IE9

Here is the code snippet I am currently using: <script> var time = new Date(); time.setFullYear(time.getFullYear() + 1, time.getMonth(), time.getDay()); expires = ";expires=" + time.toGMTString(); document.write(expires); doc ...

Tips for customizing the color of Menu in material-ui v5

I've been searching for solutions to change the background color of the Menu, but the methods I found are outdated. The use of @mui/styles and makeStyles is now deprecated, as stated in mui.com/styles/basics/#hook-api. I attempted to change the backgr ...

Exploring the functionality of dynamic component imports in jest testing

Under a specific condition, I dynamically imported a component and stored it in an object property. Then, I displayed it in the template using vue <component :is="">. Everything is functioning correctly at the component level. However, I am ...

employing a flexible array of gulp operations in run-sequence

I have a situation where I need to create gulp tasks with dynamic names and ensure that they run in sequence, not parallel. I have stored the task names in an array, but when I try to use run-sequence, I encounter an error. I suspect the issue lies in how ...

Transfer all the child nodes to the parent using the spread operator or Object.assign while preventing duplicate properties from being overwritten

I'm trying to transfer all the nodes of a child node to the parent using the spread operator or Object.assign (without relying on Lodash) while avoiding overwriting existing properties. My initial thought was to simply append the childArray to the ro ...

Tidying up JQuery with automatic selection of the next div and navigation item

My primary question revolves around optimizing the code for a functionality where clicking on 5 images reveals a related div while hiding the rest. As a newcomer to jQuery, I feel that my current implementation is somewhat messy and lengthy. Seeking advice ...

The revalidation feature in Next.js' getStaticProps function does not seem to be

https://i.stack.imgur.com/vnNMQ.png I have a question regarding my use of the getStaticProps function in index.js. I am trying to ensure that my API call runs every 60 seconds when a user visits my page, but I am experiencing issues with revalidate not wo ...