skip to Main Content

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/

3

Answers


  1. Your code is run only once when the script starts but you want to run it everytime the slide changes. Therefore, you can subscribe to the ‘slid.bs.carousel’ event which fires everytime the carousel displays a new slide.

    You can read more about the event here: http://getbootstrap.com/javascript/#carousel-events.

    // Testimonial Background from active slide
    $('#testimonial-carousel').on('slid.bs.carousel', function () {
      $("#testimonial-carousel .item.active").each(function() {
          var $myBg  = $(".testimonial-bg", this),
              $myImg = $(".testimonial-img img", this);
    
          $myBg.css({backgroundImage: "url('"+ $myImg[0].src +"')"});
    
        });
    });
    
    Login or Signup to reply.
  2. 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','.carousel-inner>.item.active');
          $myBg.css({backgroundImage: "url('"+ $img[0].src +"')"});
          console.log($img[0].src);   
      });
    

    Working fiddle

    Login or Signup to reply.
  3. There is no class called “testimonial-bg”, here is the code which should call on each slide rotate or when you need to assign background image.

    $("#testimonial-carousel .item.active").each(function() {
        $(this).css("background", "url('"+$(this).find(".testimonial-img img").attr('src')+"')" );
    });
    

    Fiddle demo link

    Cheers

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search