Assigning a background image based on the quantity of items in an array or object

I'm having trouble appending divs and setting their background image based on the number of items in an array or object. Despite adding the divs correctly, all of them end up with the same background image when only three should have it. Can someone explain why this is happening?

JS

Here is the version using an array.

var plane_images = ["images/Top.png", "images/ata21.png", "images/ata26.png", "images/Top.png", "images/Top.png"];

for(var img = 0; img < plane_images.length; img++){
    $("#menu").append("<div class='schematics'></div>");
    $(".schematics").css("background-image", "url(" +plane_images[img] +")");
    console.log(plane_images[img]);
}

This is the object-oriented version.

var Plane_Images = {
    top: "images/Top.png",
    structure: "images/ata21.png",
    electrics: "images/ata26.png",
    fuel: "images/Top.png",
    hydraulics: "images/Top.png"
}

for(var images in Plane_Images){
    var image_src = Plane_Images[images];

    $("#menu").append("<div class='schematics'></div>");
    $(".schematics").css("background-image", "url(" +image_src +")");
    console.log(image_src); 
}

It's worth noting that each console log shows the correct values being passed.

HTML

<body>
    <div id="header"></div>
    <div id="holder">
        <div id="menu"></div>
        <div id="plane_image"></div>
        <div id="sub_menu"></div>
    </div>
    <div id="footer"></div>
</body>

Answer №1

Instead of adding the element and then selecting it immediately, a more efficient approach is to create the elements one by one, style them, and then add them to the DOM.

$menu = $("#menu");

for(var images in Plane_Images){
  var image_src = Plane_Images[images];
  $schematic = $("<div></div>");
  $schematic.addClass("schematics");
  $schematic.css("background-image", "url(" + image_src +")");
  // you can log the element to the console to debug it here
  console.log($schematic);

  $menu.append($schematic);
}

By caching the menu element using this method, you avoid spending extra time evaluating the jQuery selector every iteration of the loop, resulting in faster performance as well.


If you prefer to use an Array instead of an object, you can utilize the jQuery $.each method:

$.each(Plane_Images, function(image_src) {
  $schematic = $("<div></div>");
  $schematic.addClass("schematics");
  $schematic.css("background-image", "url(" + image_src +")");

  $menu.append($schematic);
});

Answer №2

$("#menu").append("<div class='schematics'></div>");
$(".schematics").css("background-image", "url(" +image_src +")");

You are targeting all elements with the class .schematics, including ones that existed before this code block.

A more accurate approach would be:

for(var key in Plane_Images){
    var image_src = Plane_Images[key];

    $("<div class='schematics'></div>")
        .css("background-image", "url(" +image_src +")")
        .appendTo("#menu");

    console.log(image_src);
}

Answer №3

Utilizing Identifiers:

var Aircraft_Pictures = {
  top: "images/Top.png",
  construction: "images/ata21.png",
  electrical: "images/ata26.png",
  fuel: "images/Top.png",
  hydraulics: "images/Top.png"
}

var x=1;
for(var pics in Aircraft_Pictures){
  var pic_src = Aircraft_Pictures[pics];

  $("#menu").append("<div class='schematics' id='bgPic"+x+"'></div>"); // include ID
  $("#bgPic"+x).css("background-image", "url(" +pic_src +")"); // utilize ID not class
  console.log(pic_src); 
  x++; // increment x to avoid multiple IDs
}

Answer №4

You have been setting the background based on a class which is causing the last image to override all other div backgrounds. It would be better to use an id instead. You can achieve this by:

for(var img = 0; img < plane_images.length; img++){
    $("#menu").append("<div class='schematics'"+i+"></div>");
    $("#schematics"+i).css("background-image", "url(" +plane_images[img] +")");
    console.log(plane_images[img]);
}

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

Reactive form allows you to easily format dates

Currently, the date displayed is 1/4/2022. We need it to display in the format 01/04/2022. Can we achieve this formatting using reactive forms with the sample Model form provided below? Thank you. How can we format it when starting from transactionStartD ...

What is the best way to retrigger an ajax request in jQuery after it encounters an error?

In my JavaScript code, I have an AJAX request that communicates with a Rails controller to send data. If the controller detects duplicate information already in the database, it returns an 'Unprocessable Entity' error. I am looking to implement ...

Employing Ajax.Updater to retrieve a javascript file (prototype.js)

My ajax request is set up as follows: new Ajax.Updater({ success: 'footer' }, '/dyn/actions/checkSystemMessage', { insertion: 'after', evalScripts: true }); The content found at /dyn/actions/checkSystemMessag ...

How can I prevent ajax loader from overlapping headers in jquery-datatables?

Currently, I am developing a web application that utilizes jQuery data tables to load data from the server side. One issue I have encountered is that when the data table first loads, the loader covers the headers, creating a visibility problem as depicted ...

Using jQuery to Block Remote Rails Form Submission using Live() Event Handler

Having trouble preventing a remote form submission in jQuery. I have a form that is submitted remotely: <%= form_for @order, :remote => true do |f| %> When attempting to bind to the form submit event in coffee script: $('#new_order') ...

Click on the button to sort Angular data

Greetings! I am a newcomer trying to grasp the concepts of angularjs/typescript. I have compiled an array of fruits, displayed in an unordered list. My goal is to arrange them in descending order and implement a reverse search function to display the item ...

I am looking to incorporate a rounds div into the backdrop

My attempt to use border-radius did not solve my issue. I am trying to create a circular background for a specific section of the page, as shown in the image. For my first inquiry: I only want the circular background at the top of the page, not the botto ...

Exploring the concept of sharing variables between files in Node.js and JavaScript

I have a situation where I am working with files that require database access. One of the files contains code like this: ... var dynamo = new AWS.DynamoDB.DocumentClient(); module.exports.getDatabase= function(){ return dynamo; }; ... I'm curiou ...

Querying specific data from the API using unique identifiers

If the api.football-data.org/v1/competitions holds this data: { "_links": { "teams": { "href": "http://api.football-data.org/v1/competitions/444/teams" } }, "id": 444, "caption": "Campeonato Brasileiro da Série A", ...

Having Trouble Implementing Canvas in My Vue.js Project

I needed to take a screenshot in my vue.js project, so I decided to use html2canvas. Here are the steps I followed to implement html2canvas: Step 1-: Install 'html2canvas' into my project npm install html2canvas Step 2-: Import html2canvas int ...

Tracking User IDs across different domains with Piwik: a step-by-step guide using PHP and JavaScript

Is there a way to connect the IP address of the current visitor to a specific user ID using PHP in Piwik tracking, and ensure this connection is maintained across multiple (sub)domains? I have multiple (sub)domains and I want to assign a unique UserID to ...

Can CSS alone be used to provide a cover for auto-scaling images?

One common technique is using max-height and max-width to make an image automatically fit in a div, as shown below: .cover img { max-width: 100%; max-height: 100%; } But is there a way to create a translucent cover (with opacity set to 0.8) that ...

Place the div's scrollbar at the beginning of its content

Recently, I put together a custom CSS modal that includes a scrollable div (without the modal itself being scrollable). Interestingly enough, when I initially open the modal, the scrollbar of the div starts at the top as anticipated. However, if I scroll d ...

Load all HTML content from external files using a Bootstrap modal

Using Bootstrap 4.1.3 I have a specific requirement that is different from the solution provided here: Bootstrap Modal Dynamic Content The scenario involves fetching the complete modal HTML content from an external file and then presenting it as a modal. ...

Tips for synchronizing text field and formula field content on MathQuill 0.10

I am currently working on creating a WYSIWYGish input element for my formula, along with a LaTeX input element. <span id="editable-math" class="mathquill-editable"></span> The goal is to make these two elements work synchronously. Here's ...

Elements that smoothly transition in and out of view

I have implemented this effect in a project, and now I want to replicate it at both the top and bottom of the page. For example, I want elements to fade in when scrolling into view at the bottom of the page, and fade out when scrolling out of view. Simila ...

Escape sequences do not seem to be functioning properly when using innerHTML

I am facing an issue where a string containing HTML escape characters (such as < and >) needs to be rendered inside a div using innerHTML. The intention is for the escaped characters to appear as text rather than as actual HTML, but they still render ...

Calculating Two Results for Two Target Elements in Vue.js

Is it possible to have two different outcomes for result() in Vue's computed based on the element id? For instance, I'd like to return a result with commas replaced by AND for #and, and another result with commas replaced by - for #dash. https:/ ...

The loaded iframe did not deliver any valid message

Need some assistance with the following issue. Hello Ray, I have noticed that responses are coming back correctly for IE7/8 immediately. However, Firefox takes its time to upload with a progress bar indicating the process. I'm concerned that someone ...

Having an issue with retrieving value from a textfield in JavaScript

<input id="checkOldPassword" type="button" title="Check New Password" value="Check New Password" onclick="checkPassword()" /> <input id="newPassword" type="text" maxlength="8" min="8" /> <script language="javascript"> function checkPassw ...