tomc tomc - 3 months ago 9
Javascript Question

Setting background image on dynamic element

I'm trying to set a background image on a dynamically created element however it does not seem to be working. It is supposed to take the "img" property of an object that I have put into an array and then use that for the background image url.

Javascript:

var sponsorArray = new Array();

//Sponsor Constructor Function
function Sponsor(name, img, tier, url, description) {
this.name = name;
this.img = img;
this.tier = tier;
this.url = url;
this.description = description;

//A counter for the number of sponsors
Sponsor.num = (Sponsor.num || 0) + 1;

//Insert this object into the sponsors array
sponsorArray.push(this);
};

var sponsor0 = new Sponsor(
'test sponsor',
'./images/sponsors/test.png',
'Platinum',
'test.com',
'blah blah blah'
);

var initSponsors = function() {
for (var i = 0; i < sponsorArray.length; i++) {

var sponsor_image = $('<li>', {
'class': 'sponsor-logo',
'id': 'sponsor' + i,
'background-image': 'url(\'' + sponsorArray[i].img + '\')'
});

$('#logo-sponsors').append(sponsor_image);
}
};

initSponsors();


HTML:

<ul id="logo-sponsors">
</ul>


When I inspect the element it appears that it should work? I'm at a loss...

https://jsfiddle.net/qmr32463/

Answer

"background-image" is an invalid jQuery method. .css() on the other hand is valid, so

instead of

        'background-image' : 'url(\'' + sponsorArray[i].img + '\')'

Use:

        css : {
          backgroundImage: 'url(\'' + sponsorArray[i].img + '\')'
        }

https://jsfiddle.net/qmr32463/1/

Comments