Modifying the background image of div elements with JQuery in a loop function is ineffective when using Google Chrome

I am facing an issue in my application where I have a for loop to change the background image of two divs. The code snippet is as follows:

for (var i = 0; i < length; i++) {
   $("div_" + (i + 1)).css("background-image", "../imageFile.png");              
}

This code works on internet explorer, edge, and Firefox but not on Google Chrome. On Google Chrome, it only changes the last image.

Thank you!

Hello everyone, I appreciate the prompt responses from Chiristian and Nascheez! I must apologize for not including all the code initially. In the original code, I ensured that the structure was correct. It functions perfectly on other browsers. However, on Google Chrome and Opera, it displays only the image of the last div.

Here is the original code :

function testFunction() {
        $.ajax({
            type: 'post',
            url: '@Url.Action("SomeAction", "SomeController")',
            data: {

            },
            async:false,
            dataType: 'json',
            success: function(dataPieces) {

                //I receive all pieces without any errors!
                config.allPieces = dataPieces;

                for (var i = 0; i < dataPieces.length; i++) {
                    $("#div_" + (i + 1)).css("background-image", dataPieces[i].ImagePath);
                }
            },
            error: function(error) {
                alert("9- La transaction a rencontré une erreur. \n" + error.message);
            }
        });
    }

Answer №1

After carefully investigating, I have identified the solution - it appears that the change image event was triggering another event unexpectedly. This issue seems to be related to the efficiency of Google Chrome specifically.

Interestingly, other browsers do not face the same challenge as they are not as swift as Google Chrome and Opera. In response, I have adjusted my approach by implementing a parameter to prevent the unintended triggering of the additional event.

Thank you for taking the time to review and address this matter.

Answer №2

After conducting several experiments, I am intrigued by the functioning of this particular code. It appears that simply attempting to alter the background without including url() yields no results for me. Give this a try:

for (let x = 0; x < count; x++) {

   $("#section_" + (x + 1)).css("background-image", `"url(` + dataSource[x].PicturePath + `)"`);      
}

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

A comprehensive guide on troubleshooting the toggleComplete functionality for React Todo applications

When you click on an item in the to-do list, it should show a strikethrough to indicate completion. However, when I try clicking on an item, nothing happens. Here is my toggleComplete function and where I am attempting to implement it: class ToDoForm exten ...

Event emitting from a parent Vue.js component

I can't figure out why my code is not functioning properly. I have an event called 'leave' that should be triggered on blur. The components show up correctly, but the event doesn't fire when leaving the inputs. Vue.component('te ...

Is there a specific approach for linking together two AngularJs service calls and executing a function with the obtained data?

I am trying to chain two service calls together and then filter the data using a forEach loop. However, I am encountering a TypeError: "SocialMediaUserService.channelProfiles is not a function" error in Chrome. Interestingly, this code works perfectly fin ...

Using Typescript to typecast in D3.js

Utilizing the D3 graph example available here. I've defined my data object as shown below: interface ID3Data { age: string, population: number } const data: ID3Data[] = [ { age: "<5", population: 2704659 }, { age: "5-13", population: 4499 ...

Is there a way to prevent tags from wrapping and showcase them all in a single line when utilizing the jQuery select2 plugin?

I have a requirement to prevent tags from wrapping and instead display them in a single line using the jQuery TagIt plugin. Check out my preview: https://i.stack.imgur.com/lYhsi.png My goal is to have all the tags displayed on a single line without wra ...

The functionality of Jquery appears to be malfunctioning on the Drupal platform, although it performs

I've built a jQuery carousel that is fully functional when tested locally, but encounters issues when uploaded to a Drupal platform. Surprisingly, the jQuery functions properly when entered through the Console. Here's the jQuery code: carousel = ...

Ways to attribute a numeric worth to a choice in a JavaScript form

I am in the process of creating a form that allows users to customize and order pizza while showing them the invoice as they make their selections. Currently, I have successfully implemented the display of user-selected options, but I am struggling with a ...

A step-by-step guide on how to use the Google Closure Compiler: a

Is there anyone who could assist me in adding a snippet to the basic process of Google Closure Compiler? I have been trying unsuccessfully to do this via JavaScript code. I am using an example snippet from the official npm page, but when I run it, someth ...

Consistent Gaps Among Any Number of Buttons

I have a scenario where I have multiple buttons arranged in different lines. Currently, when a button doesn't fit on a line, it moves to the next line leaving blank space behind. What I want is to evenly space out the buttons that manage to be on the ...

Position a div at the bottom of a grid inside another div using tailwind CSS

https://i.sstatic.net/Clw7r.pngi am struggling with the following code <template> <div class="grid grid-cols-1 gap-4"> <div id="test" class="bg-red-700 h-screen"> <div class="grid grid-cols-1 g ...

Unable to establish connection with server through Ajax request on HTML page

I set up a NodeJs server using the Express module. However, I am facing issues with implementing an AJAX request from an HTML page using $.ajax when clicking a button. I want to retrieve data from the server in either JSON or text format but for some reaso ...

Styling based on conditions, hovering effects, and implementing ReactJS

One issue I am facing is with an anchor element within a <div>. The anchor has conditional background styling, which seems to override the a:hover style. Whether I have conditional or fixed coloring, removing the background-style from component.js al ...

Looking to locate the child div elements within a parent div

I am having trouble determining the individual lengths of child divs within parent classes that share the same name. For example: <div class="main-div"> <div class="parent"> <div class="child"></div> <div class= ...

How can I reduce the size of a Bootstrap 5 carousel that spans the entire screen?

As someone new to web development, I have found using bootstrap to be extremely helpful. However, I am currently struggling with creating a carousel for my website. My goal is to display some pictures in one corner of the page, but the carousel keeps str ...

Tips on managing multiple form data using ajax for php backend

<input type="text" value="2021-05-01" class="date" name="date"> <input type="text" value="10:00" class="starttime" name="starttime"> ...

Simultaneous display of icon and text on Bootstrap toggle button

Currently, I am utilizing Bootstrap 3 along with Jquery. Within my coding structure, there is a button that holds an icon within a span tag (specifically using the glyphicon provided by Bootstrap). <button id="swapArchived" class="btn btn-default btn-s ...

Trigger modal following unsuccessful registration

I have a method in the controller for registering users. [HttpPost] public ActionResult Register(RegisterViewModel register) { if (this.IsCaptchaValid("Captcha is not valid")) { if (ModelState.IsValid) { ...

1. Catalog of dual JSON inquiries2. Compilation of

I am struggling to understand the right way to proceed. When I run this query, I receive a JSON response containing file names: $.getJSON("http://api.server.com/my/?callback=?", function(data){ var results = []; $.each(data['resul ...

Styling Text with Shadow Effects in Mobile Web Browsers

I'm attempting to apply a text-stroke effect using text-shadow like this: .text-stroke { text-shadow: -1px -1px 0 white, 1px -1px 0 white, -1px 1px 0 white, 1px 1px 0 white; } Unfortunately, it's not rendering correctly on mobile versions of Fi ...

Why does Vue only change a specific array element without updating the DOM?

My curiosity is piqued by a puzzling issue with updating specific items in an array using Vue.js. The documentation cautions that: Due to limitations in JavaScript, Vue cannot detect the following changes to an array: When you directly set an item with th ...