Alex Zahir Alex Zahir - 7 months ago 6
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 .item.active").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:

https://jsfiddle.net/4t17wxxw/

Answer

Subscribe to slid.bs.carousel event and change the background image to the active one:

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

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

Working fiddle

Comments