Pavel Potoplyak
Pavel Potoplyak

Reputation: 141

Is it possible to dynamically add a slide to an existing Materialize Carousel?

I am able to create a carousel as described here. The carousel appears and works properly.

Later on I would like to add an additional slide:
$(".carousel").append('<a class="carousel-item active" href="#six!"><img src="http://lorempixel.com/250/250/nature/6"></a>');

However, this does not appear to work as the slide does not get added to the carousel.

Is adding slides to an initialized carousel not supported or is this an issue on my end?

Upvotes: 5

Views: 3812

Answers (2)

Diego Troiti&#241;o
Diego Troiti&#241;o

Reputation: 321

I had the same problem, but I'm using the slider. (http://materializecss.com/media.html#slider)

To resolve this, it was necessary to clear all items, re-add items with the new one, and then re-bind the slider.

Follow example: https://codepen.io/troits/pen/QvdZov

let itens = [];
function addItem(){  
  $('.slides').empty();
  $('.slider > .indicators').detach();

  itens.push(createItem());

  for(i in itens){
    $('.slides').append(itens[i]);
  }

  $('.slider').slider();  

  showItem(i);
}

function showItem(i){
  $('.slider > .indicators > .indicator-item')[i].click();
}

Upvotes: 1

Luke
Luke

Reputation: 2400

Sure it is. I haven't seen any solution in the internet. I believe that there might be a better and smoother solution but this one is mine.

All you need to do is after adding your new items remove the initialized class from already initialized main carousel div and reinitialize it.

//init carousel
var slider = $('.carousel');
slider.carousel();

//add a new item
slider.append('<a class="carousel-item active" href="#three!"><img src="http://lorempixel.com/250/250/nature/3"></a>');

//remove the 'initialized' class which prevents slider from initializing itself again when it's not needed
if (slider.hasClass('initialized')){
    slider.removeClass('initialized')
}

//just reinit the carousel
slider.carousel(); 

full working fiddle: https://jsfiddle.net/8tq4ycm3/

Upvotes: 8

Related Questions