Sander Schaeffer
Sander Schaeffer

Reputation: 2827

Append a background image based upon their data-attribute via jQuery?

I'm probably missing some basic thing.. oh well, you guys probably know.

To make things a bit more dynamic, I would like to have specific objects have a background-image added by their unique data-attribute. Their data attribute will be the file name, while the path will always be same, printed already in the jQuery.

I know the problem lies within the image URL path, because the quotes aren't completed before the first '+'.. But how to fix that?

Html:

<div class='FPNewsitem' data-imgname="hallo"></div>

jQuery

$(document).ready(function() {
    $('.FPNewsitem').each(function() {
        var itemImage = $(this).data("imgname");
        $(this).css("background-image", "url('../images/newsitems/" + itemImage + ".jpg');");
    });
});

What am I doing wrong?

update: JSFiddle

Upvotes: 0

Views: 72

Answers (2)

Sundar Rajan
Sundar Rajan

Reputation: 133

Check this out this may help u out

Use .css $(this).css instead of attr

$(this).css

Jsfiddle

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59232

*This answer was given before OP changed the code.

There is no attribute called background-image. What you need is css which is used to style the elements. You don't need ; when you use my code.

$(this).css("background-image", "url('../images/newsitems/" + itemImage + ".jpg')");

Check out more about jQuery.css

Upvotes: 4

Related Questions