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

Having trouble with Discord.js version 12 and the messageReactionAdd event not triggering properly?

client.on('messageReactionAdd', (reaction, user) => { console.log('If you see this I actually work...'); }); I am having some trouble with my code. Despite setting up a simple console log, it seems like the code is not running prope ...

Addressing a particular scoping concern within jQuery

Often I come across this specific pattern. Could someone please provide me with a canonical method of ensuring that only image1 is displayed once? In example two, it works flawlessly - but the reason behind its success eludes me. Any insights or explanat ...

Activating the Play button to start streaming a link

Recently delved into the world of Ionic 4 and Angular, so definitely a beginner :) Purchased a UI Template from code canyon but didn't realize I needed to code the music player part. Been trying to get a music stream playing but no luck. Came across ...

"Enhance your website with jQuery autocomplete: displaying and structuring various elements

Finding the right jquery/ui autocomplete tutorial can be overwhelming, as there are numerous different approaches available. It's challenging to determine the correct method, understand why it's necessary, and learn how to enhance it. After succ ...

Validation is not being applied to the radio button

Link: Issue with Form I've encountered a problem with my script that is meant to validate and submit a form, similar to this working example: Form in Working Order Unfortunately, the script is not functioning as intended on the first link. The Java ...

Encountering a problem when attempting to send an HTML email through PHP

Trying to use PHP to send email within an HTML code snippet. Here's the code I've written: <?php if($_SERVER['REQUEST_METHOD'] == 'POST') { if ( mail ('<a href="/cdn-cgi/l/email-protection" class="_ ...

Is it possible to have scope inherit from an object in AngularJS?

Imagine creating an app like this: <script> myArray=<?php echo $array;?>; app={ myArray:myArray, myIndex:myArray.length-1, back:function(){this.myIndex--;console.log("You clicked back");}, forward:function(){this.myIndex++} } ...

Exploring NodeJS and ExpressJS: Unveiling the significance of routes/index.js

Can you explain the function of this particular file? Does this file handle all the GET and POST requests in a project? If so, wouldn't it become excessively long and complex for larger projects? I encountered an issue when trying to call a POST re ...

Arranging a collection of objects (Displaying information in a random sequence)

Here is a summary of the data returned in a shortened version: var array = [{ "response": { "itineraries":[ { "price": { "totalPricePerPassenger":"104" ...

Deliver a response to recipients through the "button" feature within the WhatsApp cloud API

I'm working on building a chatbot for my booking company. Here is an outline of my initial bot flow: const axios = require("axios").default; function initialize_bot(message, phone_number, access_token, sender, username) { if (message === ...

What purpose does the next() function serve in Express.js?

Using this script to kickstart my next js app. I can't share the entire script, but I do need some assistance with the following: What is the purpose of compression? What is the importance of using helmet? What does next({dev}) do? const express = re ...

Switch the Ionic Slide Box to the "does-continue" setting

Currently in the process of constructing a slide-box containing numerous items. I've borrowed the code from the example provided here for an infinite number of items, and it's performing well. However, I have a considerable yet finite amount of ...

Converting a Number from Negative to Positive in JavaScript and Representing it as 32 Bit Binary

I am facing an issue with converting a number to 32-bit binary data. While converting to 16 or 8 bits works fine, the result is incorrect when attempting to convert to 32 bits. For example, for 8 bits: -1 & 255 //result -> 255 or -1 & 0xFF //r ...

Center and justify image inside flexbox using MUI

Can someone explain why my image appears centered but not justified? I'm feeling confused about this. <Box sx={{ display: 'flex', minHeight: '100vh', alignItems: 'center', flexGrow ...

Creating dynamic URL routes for a static website using Vue

I am facing a challenge with my static site as I am unable to add rewrites through htaccess. Currently, our site is built using Vue on top of static .html templates such as \example\index.html. When I want to create a subpage within this layout, ...

Is it possible for a table row's cell to determine the value of the cell in the row above it?

Let me illustrate my issue with an example. Consider the following table: <table> <tr> <th>First</th><th>Second</th><th>Third</th> </tr> <tr> <td>A</td><t ...

By utilizing the body element as the container instead of a div, the content shifts to the left by eight pixels

When the body is used as the wrapper instead of a div, the content shifts eight pixels to the left (on a 1920×1080 display) when it extends below the fold. The examples below illustrate this difference in code snippets. Please note that the variance is on ...

What is the best way to send back data as a response after making a $.post request in PHP?

Looking to set up a basic post function using jQuery that takes the client's name as input and returns their information (address, phone, age, etc.). Here's what I have so far: Script: $(document).ready(function(){ $("#getClientInfo").on(&a ...

CSS animation for input range slider

Is there a way to create smoother animations for the input[type="range"] element, especially when dealing with short audio files? You can check out my Codepen where I've been experimenting with solutions using a short audio file: Codepen Link I am s ...

When integrating string variables into JavaScript regular expressions in Qualtrics, they seem to mysteriously vanish

I have been working on a project to analyze survey responses in Qualtrics by counting the number of matches to specific regular expressions. For example, whenever phrases like "I think...", "In my opinion," are used, the count increases by one. Below is t ...