Reputation: 199
I am dynamically generating HTML that is outputted like this. The [uri]
represents the absolute URL for an image. Each block of HTML has a different image. I need to dynamically make this url the background image for each rotation-bg
.
<div class="rotation-bg">
<span class="url visuallyhidden">[uri]</span>
</div>
<div class="rotation-bg">
<span class="url visuallyhidden">[uri]</span>
</div>
<div class="rotation-bg">
<span class="url visuallyhidden">[uri]</span>
</div>
...
I was able to do this with one block of HTML using the code below. The problem is that there are multiple blocks of HTML, so the variable no longer works. I need to target each block individually.
var bgImg = $('.rotation-bg .url').text();
$('.rotation-bg').css('background-image', 'url(' + bgImg + ')');
I am able to cycle through each block using the code below, but am not sure how to take this variable change the background image for each block.
$('.rotation-bg .url').each(function(){
var bgImg = $(this).text();
$('.rotation-bg').css('background-image', 'url(' + bgImg + ')');
});
Upvotes: 0
Views: 106
Reputation: 146
You're actually really close. In your each function you are targeting all of the .rotation-bg divs at once so they will all wind up with whatever the last image URL is as their background. If you change that to target the parent of the .url span that you're targeting it will hit each parent individually.
$(this).parent().css('background-image', 'url(' + bgImg + ')');
JS fiddle here - http://jsfiddle.net/9D89h/
Upvotes: 1