How to use jQuery to set a background image using CSS

I've been working on setting backgrounds dynamically with a jQuery script, but it seems like the .css function is not working as expected. Here's the code snippet:

$(document).ready(function () {

    $(".VociMenuSportG").each(function () {

        var fullHref = $(this).find('a').attr('href');
        console.log(fullHref);
        var pos = fullHref.indexOf("IDSport=") + 8;
        console.log(pos);
        var sportNum = fullHref.substr(pos, 3);
        console.log(sportNum);
        var imageName;

        switch (sportNum.toString()) {

            case '523':
                imageName = "../Images/soccer_ball01.png";
                break;
            case '468':
                imageName = "../Images/soccer_ball01.png";
                break;
        }

        console.log(imageName);
        $(this).css('background-image', 'url (' + imageName + ')');

    });
});

The script loops through each item with the class "VociMenuSportG", retrieves the link path from the list item, and then sets the background image of that list item. Despite running without errors and confirming the correct path via console.logs, the background-image doesn't get set. I'm starting to question if I might be using the .css function incorrectly somehow?

EDIT

I've attempted changing the image paths to absolute paths instead of relative ones, but unfortunately, that didn't solve the issue.

Answer №1

The problem you are facing pertains to the spacing between url and (. Simply eliminate the space, and it should function properly.

 $(this).css('background-image', 'url(' + imageName + ')');

Answer №2

Not sure what the issue might be, but a good starting point is to try setting another CSS property to see if that resolves the issue.

For example: Css('border', '1px solid red')

I also noticed a space between 'url' and '('. It's possible that could be causing the problem.

If changing the property doesn't work, have you attempted manually setting it through the browser debug toolbar to confirm that the URL is correct? The use of '../' in your URL raises some doubt, as typically this is used in CSS files to navigate from /css to /images. Since you are not in the /css directory, try using '/Images/soccer_ball01.png' instead.

(Edit: I see someone else already posted an answer, so hopefully this provides additional guidance for debugging in the future!)

Answer №3

To correctly utilize that method, the following format should be used:

$(this).css( { 'background-image' : 'url(' + imageName + ')' } );

If you had provided a fiddle, I could offer more detailed assistance in resolving the issue.

Answer №4

Tip:

Consider utilizing the background property instead of background-image. Here is an example:

$(this).css('background', 'url(' + imageUrl + ')');

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

Retrieve the values of an array using a foreach loop with data retrieved from an

Hey there! Here is the array obtained from an ajax response: [{"qty":1,"name":"7-test-Professional","part_number":"12231","list_price":"800"}, {"qty":1,"name":"Senior Professional Forester","part_number":"","list_price":"97.000000"] I'm attempting t ...

Spinning text within a circular rotation in CSS

Looking for guidance on how to center the "hallo" text inside a circle? Currently experiencing issues with the circle display in IE8 and Firefox. Any suggestions on how to fix this would be greatly appreciated. And here is the link to my code snippet: CSS ...

Substitute the attributes of one object with those of another

Alright, I'm revising this because it seems to be causing confusion. Imagine you have two items x and y. What I aim to do is swap all the characteristics of x with those of y. (Please note that this isn't your usual duplication process where a ...

Assign the input value to the success callback for the ajax request

I am facing an issue with setting the data returned from a success callback in an AJAX request as an input value. It seems like this problem is arising because I am using the AJAX request within an event function (.on). For updating the specific input, I b ...

Is the iCheck feature designed to block all parent click events?

I've developed an "interaction tracker" system that collects anonymous data on clicked page elements. By implementing an event listener for clicks on the body, I can track interactions with any element on my site successfully. However, interestingly ...

Error importing React Icons with the specific icon FiMoreHorizontal

Currently following a guide to create a Twitter-like application and I need to add the following imports: import { FiMoreHorizontal } from 'react-icons/fi' 2.3K (gzipped: 1K) import { VscTwitter } from 'react-icons/vsc' 3.1K (gzipped: ...

The input element captures the exact x and y coordinates of where the mouse was clicked

I have a requirement to submit a page, and I have opted to utilize the <input> element for this purpose with an image that zooms slightly when hovered over. Due to the unusual nature of my query, I was unable to find any relevant information about t ...

Creating multiple child processes simultaneously can be achieved by spawning five child processes in parallel

My goal is to simultaneously run five spawn commands. I am passing five hls stream urls to the loop, and these streamlink commands are meant to record the video for 5 seconds before terminating those processes. I have attempted various async methods but a ...

Updating the @mui/x-data-grid table dynamically upon fetching new data

Seeking assistance regarding updating data in the DataGrid component from the @mui/x-data-grid module within a React application. Specifically, I am facing challenges in refreshing the table after retrieving data from an API using react-query. Despite succ ...

Tips for optimizing Firestore database requests on the web to minimize the number of API calls

On my product page, every time a user presses F5, the entire list of products gets loaded again. I am looking for a way to save this data locally so that it only needs to be updated once when a new product is added, instead of making multiple API calls. ...

Issues with aligning center vertically and horizontally using flexbox are causing unexpected behavior

Understanding the basic concepts of centering a flex container using justify-content:center and align-items: center, I am facing an alignment issue with my box. Can anyone help me with this? This is what I have attempted so far: <template> <di ...

Error detected in JSON syntax... Where is it hiding?

After running the code through jsonlint, it flagged an error on line 17. However, upon close inspection of the file which contains about 1000 lines, I couldn't pinpoint the issue. It's possible that the problem lies further down the file, but I w ...

Enhancing a Stripe customer object with additional metadata

While setting up a payment system using Stripe, I encountered an issue when trying to add metadata to the customer object. Specifically, I wanted to include my workspace id in the metadata property of the customer. However, upon executing the code below, I ...

Using Firestore startAt() with Redux: a comparison of serializable and non-serializable scenarios

I find myself at a pivotal moment in my Firebase project and am seeking some general guidance. Here are the key points as I have gathered them through my research: When it comes to Firestore queries, there is a useful feature for pagination called startAt ...

Looking to incorporate new values without replacing them in react.js and mongoDB

function getFilterQuery() { const completedWorkState = WorkflowStates.findOne({title: 'Completed'}); const inProgressWorkState = WorkflowStates.findOne({title: 'In Progress'}); const identifiedWorkState = WorkflowStates.findOne ...

When selecting the "Open Link in New Tab" option in Chrome, the Angular app's routing will automatically redirect to the login page

I am facing a peculiar issue in my Angular 2 application that I need help troubleshooting. Currently, the routing within my app functions as intended when I click on links to navigate between different components. Here is an example of how the routing path ...

Instructions on utilizing module.exports to export an async function

I am facing an issue with returning the result of an async function to the route I am calling. How can I resolve this successfully? My goal is to export a token from file token_generator.js and display it on route ('/') using Express. The functi ...

Sharing data between controllers using factory in AngularJS is not supported

I attempted to share data between two controllers by using a factory. However, it seems that the data is not being shared properly between the two inputs. In the AppCtrl controller, I set Data.FirstName to be equal to lattitude. But when I switch over to ...

Steps for displaying a div when clicking a link in the navigation

Hello there, I'm from the Netherlands so please excuse any mistakes in my English. I will do my best to explain my question clearly.... Objective The goal is to have a navigation bar where each item, when clicked on, will display a div with content ...

Understanding the concept of "this" within a callback situation

Given class functions game.PlayScreen = me.ScreenObject.extend({ onResetEvent: function() { this.setAll(); //calls setAll(), which calls setGlobals() this.saveNextLevelData(this.setAll); }, saveNextLevelData : function (cal ...