Michael
Michael

Reputation: 43

jQuery setting css background image

I am setting backgrounds dynamically using a jQuery script however the .css function does not seem to be working. Here is the script:

$(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 runs through each item (VociMenuSportG), finds the path of the link in the list item and then sets the background image of the list item. The script successfully runs with no errors and using the console.logs I can see the correct path is chosen. But the background-image simply does not set ? I am wondering if I am maybe using the .css function incorrectly somehow ??

EDIT

Tried setting the paths of the images to absolute paths rather than relative ones but still no luck

Upvotes: 0

Views: 104

Answers (4)

Gangadhar Jannu
Gangadhar Jannu

Reputation: 4414

Suggestion:

You can use background instead of background-image like this way:

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

Upvotes: 0

vahidseo
vahidseo

Reputation: 461

Correct form of using that method is this:

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

I would give you more info to fix it, if you had created a fiddle.

Upvotes: 0

vrijdenker
vrijdenker

Reputation: 1431

I'm not sure what's wrong, but first of all try to set another css property and see if that works.

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

Also I spotted a space between 'url' and '('. Maybe that doesn't work?

If it doesn't: have you tried setting the property manually from the browser-debug-toolbar to test if the URL you use is in fact the right one? The fact that you use '../' in your url makes me doubt. The ../ is often being used in css files to point from /css to /images for example. But in this case you are not in /css. So try: '/Images/soccer_ball01.png' for instance.

(Edit: while writing the answer was already posted, but well, maybe this will clarify how to debug next time... :) )

Upvotes: 0

Suresh Ponnukalai
Suresh Ponnukalai

Reputation: 13988

The issue in your case is space between url and (. Remove the space it will work.

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

Upvotes: 2

Related Questions