Alex Zahir Alex Zahir - 9 months ago 25
Javascript Question

jQuery clone an image with a class of active and set it as background image of a div

I am using twitter bootstrap's default carousel for a simple slider. What I want to achieve is that whichever item is active, the img inside that item should also be cloned and set as the background image of the div with the class of 'testimonials-bg'.

I have tried the following code but it does not seem to be working:

$("#testimonial-carousel").each(function() {

var $myBg = $(".testimonial-bg", this),
$myImg = $(".testimonial-img img", this);

$myBg.css({backgroundImage: "url('"+ $myImg[0].src +"')"});


I have made a Fiddle for this:


Subscribe to event and change the background image to the active one:

var $myBg  = $(".testimonial-bg");

  $('#testimonial-carousel').on('', function () {
      var $img = $('img','.active');    
      $myBg.css({backgroundImage: "url('"+ $img[0].src +"')"});

Working fiddle