Trouble Initializing a Dynamically Built Carousel

I am trying to dynamically create a Materialize carousel (NOT a slider) from Flickr photos, but I was not able to get the pictures to change. The picture that shows is always the last photo taken by Flickr, so I feel like something is scrolling, but it just does not continue to rotate the way the carousel should use it.

I looked at SO and Google answers, but 99% of the information is Bootstrap. I added an active class to the first element and tried to initialize the carousel both inside html and from javascript, but none of them helped. Here is the html code:

<div class="carousel initialized" id="flickrPic"></div> 

and JS:

 $.ajax({ type: "GET", url: flickrApiUrl + $.param(flickrApiParams), success: function(response) { var flickrPetPics = response.photos.photo for(i=0; i<flickrPetPics.length; i++) { var newSlide = makeFlickrCarousel(flickrPetPics[i]); $('.carousel-item').first().addClass('active'); $('#flickrPic').carousel(); $("#flickrPic").append(newSlide); } } }); function makeFlickrCarousel(photoInfo) { var flickPicUrl = "https://farm" + photoInfo.farm +".staticflickr.com/"; flickPicUrl += photoInfo.server + "/" + photoInfo.id + "_" + photoInfo.secret; flickPicUrl += "_q.jpg"; //Build carousel pieces var newItem = $("<a>").addClass("carousel-item"); var flickrImg = $("<img>").attr("src", flickPicUrl); newItem.append(flickrImg); return newItem; } 

Thanks for the help!

+7
javascript jquery html5 carousel materialize
source share
1 answer

You must remove the class . initialized from the carousel div container and transfer initialization $('#flickrPic').carousel() after the for loop as follows:

  ... for(i=0; i<flickrPetPics.length; i++) { var newSlide = makeFlickrCarousel(flickrPetPics[i]); $('.carousel-item').first().addClass('active'); $("#flickrPic").append(newSlide); } $('#flickrPic').carousel(); // <-- Initialize the carousel after the loop has created the carousel markup ... 
0
source share

All Articles