Question

I have to add different images in a carousel. The code i'm using loops through all the image source and inserts last image in all image section of the carousel. How can i insert different image in each carousel image? What should i change in the following code?

This is the carousel part:

    <div id="carousel">
        <!-- for loop to avoid repeatition  -->
        <!-- for loop begins -->
        <?php for($i = 0; $i < 6; $i++): ?>
        <div class="carousel-feature">
          <a href="#"><img class="carousel-image" alt="" src="" height="365" width="620"></a>
          <div class="carousel-caption">
            <p></p>
          </div>
        </div>
        <?php endfor; ?>
        <!-- End of for loop -->
    </div>

this is my jquery code:

                for(var k = 0; k < images.length; k++){

                  //iterating through each child of id carousel
                  $('#carousel').children('.carousel-feature').each(function(){
                    //loops through the images

                      //changing the alt attribute of image tag
                      $('.carousel-image').attr('alt', images[k].alt);
                      //changing the src attribute of image tag
                      $('.carousel-image').attr('src', images[k].src);
                      //changing the text in paragraph tag inside div with class 'carousel-caption'
                      $('.carousel-caption p').text(images[k].caption);

                  });
                }
Was it helpful?

Solution

Try like following:

var k=0;
$('#carousel .carousel-feature').each(function(){                    
                  $(this).find('img:first').attr('alt', images[k].alt);
                  $(this).find('img:first').attr('src', images[k].src);
                  $(this).find('.carousel-caption').children().text(images[k].caption);
                  k++;
              });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top