0

I have a Bootstrap carousel. I wish to dynamically populate the background for each slide with jQuery and CSS so that I can set background-size: cover; for each slide.

I have an attribute on each slide data-src which is populated with each slides corresponding image location.

E.G.

data-src="http://www.clickwallpapers.com/wp-content/uploads/2014/02/Wallpapers.jpg"

My jQuery code picks this up and applies it to the CSS for the item.

jQuery

srcImage = $('.item-image').data('src');
$('.item-image').css('background-image', 'url("' + srcImage + '")');

This code works if there is only one slide, however when new slides are introduced it takes the image of the last slide and applies it to all of them, because they all use the same class.

I had tried using the $(this) selector as below, but that broke the whole thing.

$('.item-image').css('background-image', 'url("' + $(this).data('src') + '")');

Can someone point me in the right direction to grab the data attribute for each individual item?

JSfiddle of what I have so far

1 Answer 1

3

Use the function overload of .css:

$(".item-image").css("background-image", function() {
    return 'url("' + $(this).data('src') + '")';
});

Updated jsFiddle

Sign up to request clarification or add additional context in comments.

1 Comment

I knew it would be something simple. Thanks for answering. I'll select yours as the answer when the timer is removed.