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

Linking query branches without encountering the "Exceeded the number of hooks rendered during the previous render" error

This apollo client utilizes a rest link to interact with 2 APIs. The first API returns the value and ID of a record, while the second API provides additional information about the same record. I combine this information to render the content without using ...

Is there a way to incorporate pseudo-dynamic css into my projects?

I'm struggling with managing custom colored elements on my website. For instance, I have a hundred navigation squares on the site, each with its own unique color. The only solution I can think of is creating separate CSS classes for each color, but t ...

Take off the wrapping from the package

I need help with my code on how to remove the wrapper span tag without removing the text. <ul> <li> <a href="#"> </a> <ul> <li> <a href="#"> ...

Provide spacing on the sides for a background position

Is there a way to evenly space my background image with 10px margins on all sides instead of just the left side? Currently, it's only working on the left side. .login-page { display: flex; flex-direction: column; background: url("../src/As ...

Tips for opening a new browser tab

I'm having trouble getting my code to open in a new browser tab. Can someone help me figure out what's wrong? function getWaterMeterList() { // alert("ON"); var BillingPeriod = $('#BillingPeriod').val(); $.ajax({ ur ...

What steps can I take to fix error TS7015 in my TypeScript, Next.js, and React application when I encounter an index expression that is not a number data type?

I encountered an error stating "Element implicitly has an 'any' type because the index expression is not of type 'number'.ts(7015)" The file I imported is import { useAmazon } from "@context/amazon"; I used it as follows con ...

Converting MySQL to JSON leads to an issue where the Google visualization chart appears empty, showing no data

I have been experimenting with code to generate a pie chart using data retrieved from a database. Here's the snippet I am currently working with: <script type="text/javascript"> google.charts.load("current", {packages:["corechart"]}); googl ...

Check the input text using jQuery with various validation criteria

When I enter an alphanumeric code into a form, I need to validate it. After entering the code and clicking on the submit button: If there is an error in the text, an error message will be displayed. else a success message will appear upon submis ...

The production build encountered an error after upgrading Angular due to a problem with document.documentElement.setAttribute not being recognized

Recently, I updated my application to Angular 16 and the upgrade was successful. The application is running smoothly without any issues. However, when I attempted to run the command for a production build, ng build --configuration=production I encountere ...

Tips on fetching the ID of the selected option using JavaScript without relying on jQuery

Looking to print the selected option ID using pure Javascript (not JQuery) for multiple select tags. If we have more than one select tag, how do we achieve this? <select onchange="showOptions(this)" id="my_select1"> <option value="a1" id="ida ...

Icons that are clickable in ionic

I have successfully created a list card with 2 icons in each row. However, I am facing a challenge in making these icons clickable without disrupting the layout of the list. I attempted to add an ng-click to the icon element, but it did not work as expecte ...

Switching out text when hovering with Jquery or JavaScript

Is there a way to use jQuery or JS to make the text and icon disappear when hovering over a div, and replace it with "Read More"? I've looked at some guides but they only remove one line of text instead of clearing the entire div and displaying "Read ...

Incorporating CSS into React.js applications

I am currently working on a project using MERN.io. In my project, I am utilizing the React.js component Dropdown. However, the Dropdown component does not come with its own style and CSS, resulting in no styling at all. ... import Dropdown from 'rea ...

Implementing a div element within an autosuggest feature

i am currently integrating the bsn autosuggest into my project could someone please guide me on how to insert a div in the result so that it appears like this <div style="left: 347px; top: 1024px; width: 400px;" class="autosuggest" id="as_testinput_x ...

Optimizing AngularJS performance with REST service caching

My AngularJS application requires caching of REST service responses, and I've come across libraries like angular-cached-resource that store data in the local browser storage. However, there are times when certain cached responses need to be deleted d ...

Creating a JavaScript function triggered by a click event that will redirect to

I'm attempting to create an onclick function that will redirect you to a new page when you click on a div element, much like the A + href attribute in HTML. Any suggestions on how to achieve this? Should I just add an A tag inside the div? I'm un ...

Importing D3 data from CSV files using the "%" symbol

I am trying to import a CSV file with the following data: Month, Ratio January, 0.19% February, 0.19% March, 0.19% April, 0.18% The current code snippet I'm using is as follows: d3.csv("month_ct.csv", function(d) { return { month: d ...

Table pagination in Mat is experiencing overflow, and the button styles have also been customized for a unique look

I implemented a mat paginator feature, however, I am facing an issue where the alignment of items per page options is not correct. Below is the snippet from component.html file: <div class="table-responsive" *ngIf="resultssummaries"> &l ...

What is preventing me from translating an element using transform: translateY()?

I attempted to move the letter 'h' down by 40px on its own, but the translation only seems to work if I relocate the entire word. I also experimented with positioning 'h' absolutely relative to the parent element, but then 'ello&ap ...

Retrieving the response data from a getJson request

I am currently working on implementing a function that will perform an action based on the response text received from a specific ajax call. However, I am struggling to access the response text field in my code. Here is the snippet: var response = $.getJS ...