Reputation: 2827
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
Reputation: 133
Check this out this may help u out
Use .css $(this).css instead of attr
$(this).css
Upvotes: 1
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